Level:
Medium
题目描述:
Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.
For example, given n = 3, a solution set is:
[
"((()))",
"(()())",
"(())()",
"()(())",
"()()()"
]
思路分析:
用left和right代表左括号和右括号的剩余数,初始值为n,利用回溯的思想解题,当出现left的值大于right的值时,说明串中的右括号多于左括号,()),这种直接错误返回,如果出现left和right都为零则是满足情况的一个串。
代码:
public class Solution{
public List<String>generateParenthesis(int n){
List<String>res=new ArrayList<>();
if(n<=0)
return res;
int left=n;
int right=n;
String str="";
help(left,right,res,str);
return res;
}
public void help(int left,int right,List<String>res,String str){
if(left<0||right<0||right<left)
return;
if(left==0&&right==0){
res.add(str);
return;
}
help(left-1,right,res,str+"(");
help(left,right-1,res,str+")");
}
}