[LeetCode] 22.Generate Parentheses

来源:互联网 发布:python 时间精确度 编辑:程序博客网 时间:2024/06/06 05:18

思路:
又一个dfs问题, 回溯法很容易能够解决, 要注意只有剩下的右括号比左括号多的时候才继续进行下去

void dfs(vector<string>& res,             string& candidate,             int nLeft,            int nRight) {    // 剪枝, 左括号要剩的多了肯定不是合法字符串    if (nLeft > nRight) return;    if (! nRight)        res.push_back(candidate);    else {        if (nLeft) {            candidate += '(';            dfs(res, candidate, nLeft - 1, nRight);            candidate.pop_back();        }        candidate += ')';        dfs(res, candidate, nLeft, nRight - 1);        candidate.pop_back();    }   }vector<string> generateParenthesis(int n) {    vector<vector<string>> res;    string candidate = "(";    dfs(res, candidate, n - 1, n);    return res;}
0 0
原创粉丝点击