设左右括号的个数分别为left和right,则需要满足以下规律:left <= n && right <= right。所以在每一次递归中需要考虑两种变量的变化。以 left = 2, right = 0为例, 满足第一个条件,则求解handle(3,3,0,"(((", result)分支下所有满足条件的情况,之后再考虑handle(3,2,1,"(()", result)分支下所有满足条件结果。两个情况只要满足条件都要进行。
public List<String> generateParenthesis(int n){ List<String> result = new ArrayList<>(); if (n <= 0) { return result; } handle(n, 0, 0, "", result); return result; }
privatevoidhandle(int n, int left, int right, String cur, List<String> result){ if (left == n && right == n) { result.add(cur); return; } if (left < n) { handle(n, left + 1, right, cur + "(", result); } if (right < left) { handle(n, left, right + 1, cur + ")", result); } }