22. Generate Parentheses
problem description
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:
[
"((()))",
"(()())",
"(())()",
"()(())",
"()()()"
]
algorithm thought
括号生成,首先需要知道合法的括号序列是哪样的。一个右括号前必须有一个左括号。由于题目中都是小括号号,所以这里还不用考虑其他问题。这种题显然是回溯法解决,也可以说是递归。但是不是单纯的生成所有组合,而是有条件的生成。在生成了一个左括号的情况下,才能生成一个右括号。
code
class Solution {
public:
vector<string> generateParenthesis(int n) {
if(n==0)
return {};
vector<string> res;
help(res,"",n,0);
return res;
}
void help(vector<string>&res,string tmp,int left,int right){
if(left==0&&right==0){
res.push_back(tmp);
return;
}
if(left){
help(res,tmp+'(',left-1,right+1);
}
if(right){
help(res,tmp+')',left,right-1);
}
}
};
algorithm analysis
函数中进行的都是O(1)的操作,主要需要分析函数运行了多少次。分析了很久,得出时间变化满足很复杂,这里就不分析了
Last updated