[LeetCode] 22. Generate Parentheses
2016-12-15 16:02
405 查看
题目链接: https://leetcode.com/problems/generate-parentheses/
For example, given n = 3, a solution set is:
加左括号
加右括号
因为要满足括号匹配,所以要加一个判断。可以加右括号的必要条件是当前需要的右括号
可以用反证法证明一下。
假如不满足这个条件,则右括号
所以,在进行下一轮的递归前,要判断左右括号个数的多少。
Description
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:
[ "((()))", "(()())", "(())()", "()(())", "()()()" ]
解题思路
递归回溯。需要添加一个辅助函数用来查找所有可能,在辅助函数中,每次都只有两种可能加左括号
(
加右括号
)
因为要满足括号匹配,所以要加一个判断。可以加右括号的必要条件是当前需要的右括号
)的个数大于左括号
(的个数。
可以用反证法证明一下。
假如不满足这个条件,则右括号
)的个数小于等于左括号
(的个数,那么在此之前的括号中,必定存在至少一个右括号
)没有对应的左括号
(,出现类似
())或者
)(的结果,不满足题意。
所以,在进行下一轮的递归前,要判断左右括号个数的多少。
Code
class Solution { public: void base(vector<string>& ans, int l, int r, string now) { if (l == 0 && r == 0) { ans.push_back(now); return; } if (l > 0) base(ans, l - 1, r, now + "("); if (r > l) base(ans, l, r - 1, now + ")"); } vector<string> generateParenthesis(int n) { vector<string> ans; base(ans, n, n, ""); return ans; } };
相关文章推荐
- 【C++】【LeetCode】22. Generate Parentheses
- leetcode --22. Generate Parentheses
- <LeetCode OJ> 22. Generate Parentheses
- 【Leetcode】:22. Generate Parentheses 问题 in Go语言
- LeetCode 22. Generate Parentheses
- [LeetCode] 22. Generate Parentheses
- 蜗牛慢慢爬 LeetCode 22. Generate Parentheses [Difficulty: Medium]
- Leetcode 22. Generate Parentheses(python)
- leetcode: 22. Generate Parentheses
- 个人记录-LeetCode 22. Generate Parentheses
- leetcode 22. Generate Parentheses
- LeetCode 题解(Week15):22. Generate Parentheses
- LeetCode 22. Generate Parentheses
- LeetCode 22. Generate Parentheses(java)
- 【Leetcode】22. Generate Parentheses
- LeetCode22. Generate Parentheses
- LeetCode-----22. Generate Parentheses(n个()可能的组合)
- leetcode 22. Generate Parentheses
- LeetCode 22. Generate Parentheses
- Leetcode 22. Generate Parentheses (Medium) (cpp)