22. 括号生成——LeetCode

 

心得:每一个位置可以有两个选择, ' (  '或者'  )  '   ,可以用递归解决,

把每个左括号的数量和右括号的数量的作为递归参数。判断的时候当

左括号减去右括号大于零,就是不对的。

 

代码:

 1 class Solution {
 2    List<String> list=new LinkedList<>();
 3       public List<String> generateParenthesis(int n) {
 4           int left=0;
 5           int right=0;
 6            rec("",0,0,0,n);
 7            return list;
 8         }
 9       public void rec(String str,int index,int left,int right,int n)
10       {
11           
12           if(left<n)
13               rec(str+"(",index+1,left+1,right,n);
14           if(left-right>0&&right<n)
15               rec(str+")",index+1,left,right+1,n);
16           if(left==n&&right==n)
17           {
18               list.add(str);
19               return;
20           }
21               
22       }
23 }

 

posted @ 2019-05-16 21:01  pc_m  阅读(113)  评论(0编辑  收藏  举报