题意
给定的一个n,生成n对有效的括号对
题目链接
https://leetcode.com/problems/generate-parentheses/
题解
用dfs,记当前的左括号个数为l,当前的右括号个数为r,string保存遍历到当前位置的字符串。当string的括号总共为2*n时,把string添加入答案。当左括号的个数少于n时,添加一个左括号并进入下一层dfs,然后回溯。当右括号的个数小于左括号并且少于n时(保证括号有效),添加一个右括号,然后回溯。
class Solution {
public:
vector<string> generateParenthesis(int n) {
string s = "";
vector<string> res;
dfs(s, 0, 0, n, res);
return res;
}
void dfs(string& s, int l, int r, int n, vector<string>& res) {
if(s.size() == n*2) {
res.push_back(s);
}
if(l < n) {
s += '(';
dfs(s, l+1, r, n, res);
s.pop_back();
}
if(r < n && r < l) {
s += ')';
dfs(s, l, r+1, n, res);
s.pop_back();
}
}
};
时间复杂度:指数级
空间复杂度:
O
(
n
)
O(n)
O(n)