- 题目:给定一个数字n,产生n对圆括号(例如n=2,则返回结果为[“(())”, “()()”])
- 难度:Medium
- 思路:当圆括号字符串的长度
public class Solution {
public List<String> generateParenthesis(int n) {
List<String> result = new ArrayList<>();
helper(result,"",0,0,n);
return result;
}
private void helper(List<String> list, String str, int open, int close, int max){
if(str.length() == 2*max){
list.add(str);
return;
}
if(open < max){
helper(list, str+"(", open+1, close, max);
}
//一定左括号数大于右括号数才能往字符串里加右括号
if(close < open){
helper(list, str+")", open, close+1, max);
}
}
}