22. Generate Parentheses
Description
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:
[
"((()))",
"(()())",
"(())()",
"()(())",
"()()()"
]
Solution: (Java)
class Solution {
List<String> ret = new ArrayList<>();
char[] p = {'(', ')'};
public List<String> generateParenthesis(int n) {
String combination = "";
if (n > 0)
backtrack(combination, combination, n, n);
return ret;
}
public void backtrack(String combination, String comResult, int leftcount, int rightcount) {
if (rightcount == 0) {
ret.add(comResult);
return;
}
for (int i = 0; i < p.length; i++) {
char c = p[i];
if (c == '(') {
if (leftcount > 0)
backtrack(combination + c, comResult + c,leftcount - 1, rightcount);
} else {
int strlen = combination.length();
if (strlen > 0 && combination.charAt(strlen - 1) == '(')
backtrack(combination.substring(0, strlen - 1), comResult + c, leftcount, rightcount - 1);
}
}
}
}
思路
本题的思路是 回溯法:左括号'('
还剩余有的话,直接接上左括号(类似入栈);当前栈中最上面一个字符是左括号的话,将右括号')'
连接上(类似出栈);递归出口是右括号剩余为0。代码中的combination
起到一个栈的作用。
(也可以从 leftcount
和 rightcount
从0开始累计的方式实现:leftcount < n
时添加左括号,rightcount < leftcount
时添加右括号)