您的位置:首页 > 其它

Generate Parentheses

2015-11-28 20:57 260 查看
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:

"((()))", "(()())", "(())()", "()(())", "()()()"


#include <vector>
#include <string>
using namespace std;
class Solution {
public:
vector<string> generateParenthesis(int n) {
vector<string> result;
vector<bool> path;
dfs(0,0,0,path,result,n);
return result;
}

private:
void dfs(int curr,int r,int l,vector<bool>& path,
vector<string>& result,int n){
if(curr == 2*n){
string s;
for(int i=0;i<2*n;i++){
if(path[i]==true){
s.push_back('(');
}else s.push_back(')');
}
result.push_back(s);
return;
}

if(r==l){
path.push_back(true);
dfs(curr+1,r+1,l,path,result,n);
path.pop_back();
}else if(r>l && r<n){
path.push_back(true);
dfs(curr+1, r+1, l, path, result, n);
path.pop_back();
path.push_back(false);
dfs(curr+1, r, l+1, path, result, n);
path.pop_back();
}else{
path.push_back(false);
dfs(curr+1,r,l+1,path,result,n);
path.pop_back();
}

}
};

int main()
{
Solution s;
vector<string> result;
result = s.generateParenthesis(3);
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: