题目描述:
Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.
例子(n=3):
[ "((()))", "(()())", "(())()", "()(())", "()()()" ]
分析:
题意:给定数字n,需要返回n对圆括号组成的所有合法序列的集合。
思路:由于需要返回所有结果,因此我们采用DFS搜索。我们用left和right表示已经使用的左括号、右括号的数量,判断条件如下:①如果left小于right,不符合、停止搜索;②如果left大于right,此时可以加入左括号或者右括号、继续搜索;③如果left等于right,此时可以加入左括号、继续搜索;④如果left和right某一个大于n,不符合、停止搜索;⑤如果left和right同时等于n,说明找到一组解,加入答案、继续搜索。
代码:
#include <bits/stdc++.h>
using namespace std;
class Solution {
private:
vector<string> ans;
void DFS(int n, int left, int right, string res){
// debug
// cout << "left: " << left << ", right: " << right << endl;
// Exceptional Case:
if(left == n && right == n){
ans.push_back(res);
return;
}
if(left > n || right > n){
return;
}
if(left < right){
return;
}
DFS(n, left + 1, right, res + "(");
if(left > right){
DFS(n, left, right + 1, res + ")");
}
}
public:
vector<string> generateParenthesis(int n) {
// Exceptional Case:
if(n <= 0){
return vector<string>();
}
ans.clear();
DFS(n, 0, 0, "");
return ans;
}
};