LeetCode OJ Generate Parentheses
2015-03-22 18:26
381 查看
Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.
For example, given n = 3, a solution set is:
For example, given n = 3, a solution set is:
"((()))", "(()())", "(())()", "()(())", "()()()"
class Solution { public: vector<string> generateParenthesis(int n) { ans.clear(); anAns.clear(); numPair = n; makeParentheses(0, 0); return ans; } void makeParentheses(int numL, int numR) { if (numR == numPair) { // once the number of right parentheses is equal to n, the string is one answer ans.push_back(anAns); return; } if (numL < numPair) { // whenever the number of left parentheses is less than n, we can try to push one anAns.push_back('('); makeParentheses(numL + 1, numR); anAns.pop_back(); } if (numR < numL) { // whenever the number of right parentheses is less than left parentheses's, we can try to push one anAns.push_back(')'); makeParentheses(numL, numR + 1); anAns.pop_back(); } } private: string anAns; vector<string> ans; int numPair; };
相关文章推荐
- leetcode:Generate Parentheses
- leetcode-22-Generate Parentheses
- LeetCode 22 Generate Parentheses
- [LeetCode] Generate Parentheses 解题报告
- LeetCode Generate Parentheses
- 【leetcode】Generate Parentheses
- Leetcode:Generate Parentheses
- [Leetcode]Generate Parentheses
- Leetcode 22 Generate Parentheses
- 【leetcode】Generate Parentheses
- leetcode-Generate Parentheses
- [LeetCode]Generate Parentheses
- LeetCode 20 Generate Parentheses
- LeetCode 22 Generate Parentheses
- LeetCode 131 Generate Parentheses
- LeetCode 22 Generate Parentheses
- 《leetCode》:Generate Parentheses(hard)
- leetcode-generate parentheses
- [LeetCode] Generate Parentheses
- [LeetCode] Generate Parentheses