您的位置:首页 > 其它

LeetCode-Generate Parentheses

2013-07-29 21:07 399 查看
class Solution {
public:
vector<string> generateParenthesis(int n) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
vector<string> vec;
getParenthesis("", n, n, vec);
return vec;
}

void getParenthesis(string str, int cntLeft, int cntRight, vector<string> &vec)
{
if (cntLeft == 0)
{
if (cntRight > 0)
{
getParenthesis(str + ")", cntLeft, cntRight - 1, vec);
}
else if (cntRight == 0 && str != "")
{
vec.push_back(str);
}
}
else if (cntLeft == cntRight)
{
getParenthesis(str + "(", cntLeft - 1, cntRight, vec);
}
else
{
getParenthesis(str + "(", cntLeft - 1, cntRight, vec);
getParenthesis(str + ")", cntLeft, cntRight - 1, vec);
}
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: