LeetCode | Generate Parentheses
2016-08-19 11:29
369 查看
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:
[
“((()))”,
“(()())”,
“(())()”,
“()(())”,
“()()()”
]
简单来讲就是括号匹配的问题,给定一个n,给出所有可能的括号匹配解。
递归结束条件是step==n 或者左括号的数量小于右括号
For example, given n = 3, a solution set is:
[
“((()))”,
“(()())”,
“(())()”,
“()(())”,
“()()()”
]
简单来讲就是括号匹配的问题,给定一个n,给出所有可能的括号匹配解。
递归结束条件是step==n 或者左括号的数量小于右括号
class Solution { public: int n,rawN; vector<string> generateParenthesis(int n) { vector<string> result; string temp; this->n=2*n;this->rawN=n; generate(temp,0,0,0,result); return result; } void generate(string &temp,int step,int leftCount,int rightCount,vector<string> &result){ //递归终点 if(step==n){ result.push_back(temp); return; } if(step>0&& leftCount<rightCount) return; //还可以添加( if(leftCount<rawN){ temp=temp+'('; generate(temp,step+1,leftCount+1,rightCount,result); temp.pop_back(); } //还可以添加) if(rightCount<rawN){ temp=temp+')'; generate(temp,step+1,leftCount,rightCount+1,result); temp.pop_back(); } } };
相关文章推荐
- Happy collaboration with Rmd to docx
- tjut 2647
- 标准输入流
- java实现spark streaming与kafka集成进行流式计算
- 线性回归、梯度下降(Linear Regression、Gradient Descent)
- jackson annotation 格式化
- Centos下升级linux内核时遇到的问题
- 搭建Apache+tomcat+负载均衡环境
- apk获得Android系统权限的方法
- 矩阵的正定与半正定
- 实习时遇到的大神写的代码, 自己差距还是有的,潜力巨大!加油!
- 极速入门Linux
- leetcode:二叉树之Construct Binary Tree from Inorder and Postorder Traversal
- AOE网上的关键路径-----前向星
- [展讯项目] 多个jdk版本的快速切换方法,不需要重启shell
- sql server truncate用法--清空表中所有数据
- vijos1059 积木城堡[n年浙江省队第X轮](背包的方案总数 or 01背包)
- css中的background:transparent的作用
- vijos1059 积木城堡[n年浙江省队第X轮](背包的方案总数 or 01背包)
- C语言(数据结构) - 链表的基本操作