问题描述
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:
“((()))”, “(()())”, “(())()”, “()(())”, “()()()”
思考:怎么才能吧所有结果输出并且不重复
想法:
- 1、递归,用一个char[]数组,每一位在允许的情况下要么放‘(’要么放‘)’。
- 2、测试每一种情况,如果失败则重新测试(回溯)
- 3、可以考虑图算法,节点:(x,y)目前位置的左右括号数目,边:从(x,y)到符合条件的(x+1,y)和(x,y+1)。(其中对任意节点 x>=y)
代码
public class Solution {
public List<String> generateParenthesis(int n) {
List<String> ret = new LinkedList<>();
char[] cur = new char[2*n];
cur[0] = '(';
getParentheses(cur, ret, 1, 1, n, n);
return ret;
}
private void getParentheses(char[] sb, List<String> ret, int i, int left, int total, int n){
if(total == 0){
ret.add(new String(sb));
return;
}
if(left < n){
sb[i] = '(';
getParentheses(sb,ret,i + 1,left + 1,total,n);
}
if(left + total - n > 0){
sb[i] = ')';
getParentheses(sb,ret,i + 1,left,total - 1,n);
}
}
}
DFS
class Solution {
public:
void help(vector<string> &ans, int left, int right, string now, int n){
if(right == n){
ans.push_back(now);
return;
}
if(left < n)
help(ans,left + 1,right,now + '(',n);
if(left > right)
help(ans,left,right + 1,now + ')',n);
}
vector<string> generateParenthesis(int n) {
vector<string> ans;
help(ans,0,0,"",n);
return ans;
}
};
BFS
struct Node{
int x,y;
string str;
};
class Solution {
public:
void help(vector<string> &ans,int n){
if(n == 0){
ans.push_back("");
return;
}
queue<Node> q;
Node root;
root.x = 0,root.y = 0,root.str = "";
for(q.push(root); !q.empty(); q.pop()){
root = q.front();
Node temp;
if(root.x < n){
temp.x = root.x + 1;
temp.y = root.y;
temp.str = root.str + '(';
q.push(temp);
}
if(root.y < root.x){
if(root.y == n - 1)
ans.push_back(root.str + ')');
else{
temp.x = root.x;
temp.y = root.y + 1;
temp.str = root.str + ')';
q.push(temp);
}
}
}
}
vector<string> generateParenthesis(int n) {
vector<string> ans;
help(ans,n);
return ans;
}
};