您的位置:首页 > 其它

leetcode-22-Generate Parentheses

2017-03-10 23:10 495 查看

问题

题目:[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 );
}
}

}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: