leetcode--22. Generate Parentheses
程序员文章站
2022-05-13 21:24:48
...
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:
[ "((()))", "(()())", "(())()", "()(())", "()()()" ]利用回溯算法:
如果左右括号都达到n,则push_back
如果左括号小于n,递归添加左括号的字符串
如果右括号小于左括号,递归添加右括号的字符串
class Solution {
public:
vector<string> ret;
void bt(string strin, int left, int right, int n) {
if(left == n && right == n) {
ret.push_back(strin);
}
if(left < n) {
string new_str = strin + '(';
bt(new_str, left+1, right, n);
}
if(right < left) { //here, originally I use right < n && right < left, however, the first is redundant
string new_str = strin + ')';
bt(new_str, left, right + 1, n);
}
}
vector<string> generateParenthesis(int n) {
bt("", 0, 0, n);
return ret;
}
};
推荐阅读
-
【关于栈】Valid Parentheses详解
-
javax.net.ssl.SSLException: java.lang.RuntimeException: Could not generate DH keypair 解决方法总结
-
LeetCode - 20. Valid Parentheses(0ms)
-
Generate Parentheses(C++)
-
LeetCode-32.Longest Valid Parentheses最长有效括号子串
-
Longest Valid Parentheses leetcode java (求最长有效匹配括号子串的长度)-动态规划
-
make rel Command 'generate' not understood or not applicable
-
maven archetype:generate 的进一步理解 mavenwicketAppfuseSpringScala
-
算法分析与设计丨第一周丨LeetCode(2)——Different Ways to Add Parentheses(Medium)
-
webservice is not found. Have you run APT to generate them?