- 算法
- 1.回溯法:回溯的过程是函数的进入与退出
- 2.记录左括号和右括号的数量:
- 当左括号数量小于n时继续添加左括号
- 当右括号数量小于左括号时继续添加右括号
public List<String> generateParenthesis(int n) { ArrayList<String> result = new ArrayList<>(10); backtrack("", 0, 0, n, result); return result; } private void backtrack(String string, int open, int close, int n, List<String> result) { if (string.length() == n << 1) { result.add(string); return; } if (open < n) { backtrack(string+"(", open+1, close, n, result); } if (close < open) { backtrack(string+")", open, close+1, n, result); } }