# Leetcode 22 Generate Parentheses 搜索与DP的纠结

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:

[
"((()))",
"(()())",
"(())()",
"()(())",
"()()()"
]

class Solution {
public:
void dfs(vector<string> &v,string s,int l,int r)
{
if(l==0 && r==0)
v.push_back(s);
if(l!=0)
dfs(v,s+"(",l-1,r);
if(r>l)               //左括号必须多于右括号
dfs(v,s+")",l,r-1);
}
vector<string> generateParenthesis(int n)
{
vector<string> result;
dfs(result,"",n,n);
return result;
}
};

class Solution {
public:
vector<string> generateParenthesis(int n) {
vector<vector<string>> ans(n+1);
for (int i = 0; i <= n; i++) {
if (i == 0) ans[i].push_back("");
if (i == 1) ans[i].push_back("()");
if (i > 1) {
for (int j = 0; j < i; j++) {
for (int k = 0; k < ans[j].size(); k++)  //疑似卡特兰数，只是手推了前几个看起来像，还没有证明
for (int l = 0; l < ans[i-1-j].size(); l++)
ans[i].push_back("(" + ans[j][k] + ")" + ans[i-1-j][l]);
}
}
}
return ans[n];
}
};

## LeetCode 22. Generate Parentheses 解题报告

LeetCode 22. Generate Parentheses 解题报告

## 【LeetCode】22. Generate Parentheses

【LeetCode】22. Generate Parentheses

## Generate Parentheses - LeetCode 22

• bu_min
• 2015年05月23日 20:32
• 240

## <LeetCode OJ> 22. Generate Parentheses

22. Generate Parentheses My Submissions Question Total Accepted: 74274 Total Submissions: 211279...

## LeetCode 22-Generate Parentheses

Given n pairs of parentheses, write a function to generate all combinations of well-formed parenthes...

C语言实现

## LeetCode_22---Generate Parentheses

LeetCode

举报原因： 您举报文章：Leetcode 22 Generate Parentheses 搜索与DP的纠结 色情 政治 抄袭 广告 招聘 骂人 其他 (最多只允许输入30个字)