22. Generate Parentheses
Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.
Example 1:
Input: n = 3
Output: ["((()))","(()())","(())()","()(())","()()()"]
Example 2:
Input: n = 1
Output: ["()"]
Constraints:
1 <= n <= 8
回溯算法
回溯算法,可以用排列的形式证明是不可重复的。
class Solution {
public List<String> generateParenthesis(int n) {
List<String> list = new ArrayList<String>();
helper(list, n, n, "");
return list;
}
public void helper(List<String> list, int left, int right, String s) {
if (left == 0 && right == 0) {
list.add(s);
return;
}
if (left > 0) {
helper(list, left - 1, right, s + "(");
}
if (right > left) {
helper(list, left, right - 1, s + ")");
}
}
}