https://leetcode.com/problems/generate-parentheses/
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:
"((()))", "(()())", "(())()", "()(())", "()()()"
public class Solution {
public List<String> generateParenthesis(int n) {
List<String> rst = new LinkedList<String>();
if(n<=0) return rst;
StringBuilder sb = new StringBuilder();
helper(rst, sb, n, 0, 0);
return rst;
}
public void helper(List<String> rst, StringBuilder sb, int n, int left, int right){
if(left==n && right==n){
rst.add(sb.toString());
return;
}
if(left>n || right>n) return;
if(left < n){
sb.append('(');
helper(rst, sb, n, left+1, right);
sb.deleteCharAt(sb.length() - 1);
}
if(right <left){
sb.append(')');
helper(rst, sb, n, left, right+1);
sb.deleteCharAt(sb.length() - 1);
}
}
}
空间复杂度O(n),时间复杂度O(2^n),解释见这里: