22. Generate Parentheses
2016-04-27 12:14
253 查看
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:
“((()))”, “(()())”, “(())()”, “()(())”, “()()()”
求出所以可能的括号对
递归
The idea is intuitive. Use two integers to count the remaining left parenthesis (n) and the right parenthesis (m) to be added. At each function call add a left parenthesis if n >0 and add a right parenthesis if m>0. Append the result and terminate recursive calls when both m and n are zero.
For example, given n = 3, a solution set is:
“((()))”, “(()())”, “(())()”, “()(())”, “()()()”
求出所以可能的括号对
递归
The idea is intuitive. Use two integers to count the remaining left parenthesis (n) and the right parenthesis (m) to be added. At each function call add a left parenthesis if n >0 and add a right parenthesis if m>0. Append the result and terminate recursive calls when both m and n are zero.
class Solution { public: vector<string> generateParenthesis(int n) { vector<string> res; addingpar(res, "", n, 0); return res; } void addingpar(vector<string> &v, string str, int n, int m){ if(n==0 && m==0) { v.push_back(str); return; } if(m > 0){ addingpar(v, str+")", n, m-1); } if(n > 0){ addingpar(v, str+"(", n-1, m+1); } } };
相关文章推荐
- 今天遇到一个url转码的bug
- javascript基础-实现简单功能
- 【数据结构】用模版实现大小堆、实现优先级队列,以及堆排序
- Perfect Squares
- 如何调教Android Studio-Windows安装AS后的必备工作
- python实现欧拉计划第十四题
- php.ini中.注释符号是什么?
- 报错/崩溃bug原因详解集合
- 秘密
- Android Animation Interpolator
- 数据可视化——Matplotlib模块入门(一)
- js函数传值ie下的bug
- haproxy部分参数详细说明
- JAVA_SE基础——62.String类的构造方法
- ie6表格边框不显示问题
- HTTP错误码
- 阿里云云主机挂载数据盘,格式化硬盘(新购云主机)(转)
- nginx引入rewrite文件
- [LeetCode]RemoveDuplicateLetters解题思路
- window下Solr的安装部署