22. 括号生成
回溯:
java
class Solution {
public List<String> generateParenthesis(int n) {
List<String> ans = new ArrayList<>();
backtrack(ans,new StringBuffer(),0,0,n);
return ans;
}
private void backtrack(List<String> ans,StringBuffer combine,int open,int close,int max){
if(combine.length() == max*2){
ans.add(combine.toString());
return;
}
if(open < max){
combine.append('(');
backtrack(ans,combine,open+1,close,max);
combine.deleteCharAt(combine.length()-1);
}
if(close < open){
combine.append(')');
backtrack(ans,combine,open,close+1,max);
combine.deleteCharAt(combine.length()-1);
}
}
}
时间复杂度:
空间复杂度:O(N)