选左括号还是右括号, 只有右括号的剩余数量大于左括号的剩余数量才能选
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
| class Solution { private char[] path; private List<String> ans = new ArrayList<>();
public List<String> generateParenthesis(int n) { path = new char[2*n]; dfs(n*2, n, n); return ans; }
private void dfs(int n, int left, int right) { if (left == 0 && right == 0) { ans.add(new String(path)); return ; }
int index = n - left - right; if (left > 0) { path[index] = '('; dfs(n, left-1, right); }
if (right > left) { path[index] = ')'; dfs(n, left, right-1); } } }
|