[leetcode] 22. Generate Parentheses
2016-01-04 17:17
405 查看
Givenn pairs of parentheses, write a function to
generate all combinations of well-formed parentheses.
For example, givenn = 3, a solution set is:
"((()))", "(()())", "(())()", "()(())", "()()()"
这道题是生成匹配的括号对,题目难度为Medium。
比较直观的想法是在2*n个位置上逐个放置‘(’或‘)’,通过深度优先的方式生成最终的括号对。这里需要注意的是只有在左括号个数小于n时才可以放置‘(’,左括号个数大于右括号个数时才可以放置‘)’,因此需要分别记下左右括号出现的次数,下面代码中用lCnt和rCnt表示左右括号的个数。这样递归直到长度达到2*n即找到了一个结果。具体代码:
generate all combinations of well-formed parentheses.
For example, givenn = 3, a solution set is:
"((()))", "(()())", "(())()", "()(())", "()()()"
这道题是生成匹配的括号对,题目难度为Medium。
比较直观的想法是在2*n个位置上逐个放置‘(’或‘)’,通过深度优先的方式生成最终的括号对。这里需要注意的是只有在左括号个数小于n时才可以放置‘(’,左括号个数大于右括号个数时才可以放置‘)’,因此需要分别记下左右括号出现的次数,下面代码中用lCnt和rCnt表示左右括号的个数。这样递归直到长度达到2*n即找到了一个结果。具体代码:
class Solution { void genParenthesis(vector<string>& rst, string curRst, int lCnt, int rCnt, int n) { if(curRst.size() == n*2) { rst.push_back(curRst); return; } else { if(lCnt < n) genParenthesis(rst, curRst+"(", lCnt+1, rCnt, n); if(lCnt > rCnt) genParenthesis(rst, curRst+")", lCnt, rCnt+1, n); } } public: vector<string> generateParenthesis(int n) { vector<string> rst; genParenthesis(rst, "", 0, 0, n); return rst; } };
相关文章推荐
- Win2003利用dfs(分布式文件系统)在负载均衡下的文件同步配置方案
- win2003分布式文件系统(dfs)配置方法[图文详解]
- win2003分布式文件系统及其部署 图文教程
- leetcode 179 Largest Number
- leetcode 24 Swap Nodes in Pairs
- leetcode 2 Add Two Numbers 方法1
- leetcode 2 Add Two Numbers 方法2
- Hadoop2.6+jdk8的安装部署(1)——使用jar包安装部署【详细】
- Hadoop FS Shell
- DFS使用方法总结
- leetcode----Longest Substring Without Repeating Characters
- FastDFS注意事项
- 无忧技术带您预览DFS(分布式文件系统)管理控制台
- [LeetCode]47 Permutations II
- [LeetCode]65 Valid Number
- [LeetCode]123 Best Time to Buy and Sell Stock III
- [LeetCode] String Reorder Distance Apart
- [LeetCode] Sliding Window Maximum
- [LeetCode] Find the k-th Smallest Element in the Union of Two Sorted Arrays
- [LeetCode] Determine If Two Rectangles Overlap