原题链接:https://leetcode.com/problems/generate-parentheses/
我在github上的leetcode仓库:https://github.com/cooljacket/leetcodes
题意
给定一个整数n表示括号的对数,要求生成所有由n对括号组成的合法括号序列,比如n=3时,有:
[
“((()))”,
“(()())”,
“(())()”,
“()(())”,
“()()()”
]
思路
合法的括号序列,对于它的任意前缀来说,必定是左括号的数量大于等于右括号的数量的!生成的过程其实就是非常简单的dfs而已。
比如:一开始的第一位必定是’(‘,但是第二位就有两种选择了,可以是’(‘,也可以是’)’,第三位同样的道理,只要满足上述的“前缀约束”就可以了,整个伸展过程其实就是一棵二叉树,所以果断就是用dfs做了~
代码
class Solution {
public:
// 思路:其实就是非常简单的dfs
vector<string> generateParenthesis(int n) {
vector<string> seq_list;
string seq(2*n, ' ');
helper(n, 0, 0, seq, seq_list);
return seq_list;
}
private:
void helper(int n, int leftCnt, int rightCnt, string& now, vector<string>& seq_list) {
if (leftCnt == n && rightCnt == n) {
seq_list.push_back(now);
return;
}
if (leftCnt < n) {
now[leftCnt+rightCnt] = '(';
helper(n, leftCnt + 1, rightCnt, now, seq_list);
}
// 注意对于右括号数量的约束
if (rightCnt < n && rightCnt < leftCnt) {
now[leftCnt+rightCnt] = ')';
helper(n, leftCnt, rightCnt+1, now, seq_list);
}
}
};