【LeetCode】#22括号生成(Generate Parentheses)
题目描述
给出 n 代表生成括号的对数,请你写出一个函数,使其能够生成所有可能的并且有效的括号组合。
示例
例如,给出 n = 3,生成结果为:
[
“((()))”,
“(()())”,
“(())()”,
“()(())”,
“()()()”
]
Description
Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.
Example
For example, given n = 3, a solution set is:
[
“((()))”,
“(()())”,
“(())()”,
“()(())”,
“()()()”
]
解法
class Solution {
public List<String> generateParenthesis(int n) {
List<String> res = new ArrayList<>();
generate(res, "", 0, 0, n);
return res;
}
public void generate(List<String> res, String ans, int count1, int count2, int n){
if(count1>n||count2>n)
return;
if(count1==n&&count2==n)
res.add(ans);
if(count1>=count2){
String ans1 = new String(ans);
generate(res, ans+"(", count1+1, count2, n);
generate(res, ans+")", count1, count2+1, n);
}
}
}