给出 n 代表生成括号的对数,请你写出一个函数,使其能够生成所有可能的并且有效的括号组合。
例如,给出 n = 3,生成结果为:
[
“((()))”,
“(()())”,
“(())()”,
“()(())”,
“()()()”
]
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/generate-parentheses
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
执行用时 :
3 ms, 在所有 Java 提交中击败了82.97%的用户
内存消耗 :
39.2 MB, 在所有 Java 提交中击败了46.64%的用户
class Solution {
public List<String> generateParenthesis(int n) {
List<String> ans = new ArrayList<>();
correctPar(ans,"",0,0,n);
return ans;
}
private void correctPar(List<String> ans,String cur,int left, int right,int max){
if (cur.length() == max * 2){
ans.add(cur);
return;
}
if (left < max){
correctPar(ans,cur+"(",left+1,right,max);
}
if (right < left){
correctPar(ans,cur+")",left,right+1,max);
}
}
}