标签:
Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.
For example, given n = 3, a solution set is:
"((()))", "(()())", "(())()", "()(())", "()()()"
Cracking Interview 原题,递归回溯即可,只需注意右括号少于左括号。
public class Solution {
public List<String> generateParenthesis(int n) {
List<String> result = new ArrayList<>();
helper(n, 0, 0, "", result);
return result;
}
public void helper(int n, int left, int right, String cur, List<String> result) {
if (left < right) {
return;
}
if (left == right && n == right) {
result.add(cur);
return;
}
if (left <= n) {
helper(n, left + 1, right, cur + "(", result);
}
helper(n, left, right + 1, cur + ")", result);
}
}
标签:
原文地址:http://www.cnblogs.com/shini/p/4534954.html