您的位置:首页 > 其它

【leetcode】22. Generate Parentheses

2015-11-03 19:49 309 查看
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;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: