22.产生括号组
string
dfs
题面
Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses
给定int n,代表n组括号,编码生成所有有效的括号组合(即符合括号嵌套规则)
样例
given n = 3, a solution set is:
[
"((()))",
"(()())",
"(())()",
"()(())",
"()()()"
]
思路
dfs
源码
class Solution {
public:
vector<string> generateParenthesis(int n) {
vector<string> res;
dfs("", 0, 0, res, n);
return res;
}
//dfs深搜
void dfs(string tmp, int l, int r, vector<string> &res, int n)
{
if(l == n && r == n)
{
res.push_back(tmp);
return ;
}
if(l < n)
dfs(tmp+"(", l+1, r, res, n);
if(l > r)
dfs(tmp+")", l, r+1, res, n);
}
};
原文地址:https://www.cnblogs.com/yocichen/p/10874799.html
时间: 2024-10-19 14:08:45