LeetCode22. 括号生成
数字 n 代表生成括号的对数,请你设计一个函数,用于能够生成所有可能的并且 有效的 括号组合。
示例 1:
输入:n = 3
输出:["((()))","(()())","(())()","()(())","()()()"]
示例 2:
输入:n = 1
输出:["()"]
class Solution {
public List<String> generateParenthesis(int n) {
List<String> ans = new ArrayList<String>();
backtrack(ans, new char[2*n], 0, 0, n,0);
return ans;
}
public void backtrack(List<String> ans, char[] cur, int open, int close, int max,int pos) {
if (pos == cur.length) {
ans.add(new String(cur));
return;
}
if (open < max) {
cur[pos] = '(';
backtrack(ans, cur, open + 1, close, max,pos+1);
}
if (close < open) {
cur[pos] = ')';
backtrack(ans, cur, open, close + 1, max,pos+1);
}
}
}