1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| class Solution { List<String> result = new ArrayList<>(); public List<String> generateParenthesis(int n) { dfs(0, 0, "", n); return result; }
public void dfs(int left, int right, String str, int n) { if (str.length() == 2 * n) { result.add(str); } if (left < n) { dfs(left + 1, right, str + "(", n); }
if (right < left && right < n) { dfs(left, right + 1, str + ")", n); } } }
|