22. 括号生成(LeetCode中等)(DFS)
class Solution {
public:
vector<string> ans;
vector<string> generateParenthesis(int n) {
dfs(n, 0, 0, "");
return ans;
}
void dfs(int n, int lc, int rc, string path){
if(lc == n && rc == n){
ans.push_back(path); return;
}
if(lc < n) dfs(n, lc + 1, rc , path + '(');
if(rc < n && rc < lc) dfs(n, lc, rc + 1, path + ')');
}
};

浙公网安备 33010602011771号