leetcode-22-Generate Parentheses

来源:互联网 发布:威海孙小乔淘宝店 编辑:程序博客网 时间:2024/06/05 03:32

问题

题目:[Generate Parentheses]

思路

卡特兰数的思路。
任意时刻左括号的数量要多于右括号。
我的思路也很简单,那就是每一位挨个试探就好了。
搜索的思路。

至于参数传递,我没有选择引用。而是值传递,这一块我不是很熟。
传递引用后面要将变化改回来。

代码

class Solution {public:    vector<string> generateParenthesis(int n) {        std::vector<std::string> ret;        std::string s(2*n, ' ');        dfs(s, 0, n, 0, 0, ret);        return ret;    }private:    void dfs(std::string s, int depth, int n, int cnt_left, int cnt_right, std::vector<std::string>& ret){        if(depth == 2*n) ret.push_back(s);        else{            if( cnt_left < n && cnt_left >= cnt_right ){                s[depth] = '(';                dfs( s, depth + 1, n, cnt_left + 1, cnt_right, ret );            }            if( cnt_right < n && cnt_right < cnt_left ){                s[depth] = ')';                dfs( s, depth + 1, n, cnt_left, cnt_right + 1, ret );            }        }    }};
0 0
原创粉丝点击