【leetcode】22. Generate Parentheses

来源:互联网 发布:俞斌围棋软件 编辑:程序博客网 时间:2024/04/30 18:29

dfs,只要 ( 的数量小于 ) 的数量,即可以不断的dfs

/** * @author          johnsondu * @problem         Generate Parentheses * @url             https://leetcode.com/problems/generate-parentheses/ * @strategy        dfs, only if left "(" less than right ")",  then it is legal. * @status          Accepted, runtime beats 34.01% of cpp submissions. 0ms * @time            19:46, Nov 3th 2015 */class Solution {public:    void dfs(string tmp, int lf, int rt, vector<string>& ans)    {        if(lf == 0 && rt == 0) {            ans.push_back(tmp);        }            if(lf != 0 && lf <= rt) {            dfs(tmp + "(", lf - 1, rt, ans);        }         if(lf < rt) {            dfs(tmp + ")", lf, rt - 1, ans);        }    }        vector<string> generateParenthesis(int n) {        vector<string> ans;        if(n == 0) return ans;        dfs("(", n-1, n, ans);        return ans;    }};


0 0
原创粉丝点击