22、Generate Parentheses
生成括號
給定 n 對括號,請寫一個函數以將其生成新的括號組合,並返回所有組合結果。樣例
給定 n = 3
, 可生成的組合如下:
"((()))", "(()())", "(())()",
"()(())", "()()()"
分析:
代碼:
class Solution {
public:
vector<string> generateParenthesis(int n) {
vector<string> res;
dfs(res,"",n,0,0);
return res;
}
void dfs(vector<string> &res,string s,
int n,int left,int right)
{
if(left==n&&right==n)
{
res.push_back(s);
return;
}
if(left<n) dfs(res,s+"(",n,left+1,right);
if(left>right)dfs(res,s+")",n,left,right+1);
}
};