题目链接:generate-parentheses
import java.util.ArrayList;
import java.util.List;
/**
*
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 GenerateParentheses {
// 8 / 8 test cases passed.
// Status: Accepted
// Runtime: 213 ms
// Submitted: 0 minutes ago
// 时间复杂度O(2^n) 空间复杂度 O(1)
public List<String> parenthesis = new ArrayList<String>();
public List<String> generateParenthesis(int n) {
generateParenthesis(n, n, "");
return parenthesis;
}
// left 表示剩余"("数量, right表示剩余")"数量
public void generateParenthesis(int left, int right, String s) {
if(left == 0) {
while(right != 0) {
s += ")";
right --;
}
parenthesis.add(s);
return;
}
//选中"("
generateParenthesis(left - 1, right, s + "(");
//当剩余 ")" 数大于 "(" 数时,选中 ")"
if(right > left) {
generateParenthesis(left, right - 1, s + ")");
}
}
public static void main(String[] args) {
// System.out.println(Arrays.toString(generateParenthesis(0).toArray()));
}
}