标签:color stat pack back backtrack 不能 深度优先 ret oid
package leetcode; import java.util.ArrayList; import java.util.List; public class demo_22 { public List<String> generateParenthesis(int n) { List<String> list=new ArrayList<String>(); String s=""; //"("的个数 int left=0; //")"的个数 int right=0; backtrack(list, n, left, right, s); for(String ss:list) { System.out.print(ss+" "); } return list; } //深度优先生成树 public void backtrack(List<String> list,int n,int left,int right,String s) { //左括号的个数不能大于右括号 if(right>left) {return;} if(right==n&&left==n) { list.add(s); return; } if(left<n) { backtrack(list, n, left+1, right, s+"("); } if(right<n) { backtrack(list, n, left, right+1, s+")"); } } public static void main(String[] args) { // TODO Auto-generated method stub demo_22 d22=new demo_22(); d22.generateParenthesis(3); } }
标签:color stat pack back backtrack 不能 深度优先 ret oid
原文地址:https://www.cnblogs.com/Yshun/p/14822633.html