版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Neo233/article/details/83153563
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:
[ "((()))", "(()())", "(())()", "()(())", "()()()" ]
1)
class Solution {
public List<String> generateParenthesis(int n) {
List<String> list = new ArrayList<>();
backtrack(list,"",0,0,n);
return list;
}
public void backtrack(List<String> list,String cur,int open,int close,int max){
if(cur.length() == max * 2){
list.add(cur);
return;
}
if(open < max){
backtrack(list,cur+"(",open + 1,close,max);
}
if(close < open){
backtrack(list,cur+")",open,close + 1,max);
}
return ;
}
}
2)
class Solution {
public List<String> generateParenthesis(int n) {
List<String> ret = new ArrayList<>();
if (n == 0) {
ret.add("");
} else {
for (int i = 0; i < n; i++) {
for (String left: generateParenthesis(i)) {
for (String right: generateParenthesis(n - i - 1)) {
ret.add("(" + left + ")" + right);
}
}
}
}
return ret;
}
}
第一个方法中使用了回溯