Generate Parentheses
来源:互联网 发布:office 2010 for mac 编辑:程序博客网 时间:2024/06/11 05:16
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:
"((()))", "(()())", "(())()", "()(())", "()()()"
该问题和《编程之美》的买票找零问题一样,通过买票找零问题我们可以知道,针对一个长度为2n的合法排列,第1到2n个位置都满足如下规则:左括号的个数大于等于右括号的个数。所以,我们就可以按照这个规则去打印括号:假设在位置k我们还剩余left个左括号和right个右括号,如果left>0,则我们可以直接打印左括号,而不违背规则。能否打印右括号,我们还必须验证left和right的值是否满足规则,如果left>=right,则我们不能打印右括号,因为打印会违背合法排列的规则,否则可以打印右括号。如果left和right均为零,则说明我们已经完成一个合法排列,可以将其打印出来。
void generate(int leftNum,int rightNum,string s,vector<string> &result) { if(leftNum==0&&rightNum==0) { result.push_back(s); } if(leftNum>0) { generate(leftNum-1,rightNum,s+'(',result); } if(rightNum>0&&leftNum<rightNum) { generate(leftNum,rightNum-1,s+')',result); }}
另:
class Solution {public: vector<string> generateParenthesis(int n) { // Start typing your C/C++ solution below // DO NOT write int main() function vector<string> ans; getAns(n, 0, 0, "", ans); return ans; }private: void getAns(int n, int pos, int neg, string temp, vector<string> &ans) { if (pos < neg) { return; } if (pos + neg == 2 * n) { if (pos == neg) { ans.push_back(temp); } return; } getAns(n, pos + 1, neg, temp + '(', ans); getAns(n, pos, neg + 1, temp + ')', ans); }};
0 0
- Generate Parentheses
- Generate Parentheses
- Generate Parentheses
- Generate Parentheses
- Generate Parentheses
- Generate Parentheses
- Generate Parentheses
- Generate Parentheses
- Generate Parentheses
- Generate Parentheses
- Generate Parentheses
- Generate Parentheses
- Generate Parentheses
- Generate Parentheses
- Generate Parentheses
- Generate Parentheses
- Generate Parentheses
- Generate Parentheses
- 微信产品经理和架构师们是靠什么扛住了10亿个红包
- linux下添加库文件的几种方法
- Notification使用详解之一:基础应用
- VS2010远程调试C#项目
- iOS开发应用程序的沙盒(SandBox)结构
- Generate Parentheses
- Buried memory(hdu 3007)
- coredata and tableview
- Notification使用详解之二:可更新进度的通知
- 是不是转向GO语言
- air文件打包成exe
- sql个人总结4
- Struts+Spring+Hibernate&Struts2+Spring+JPA
- QString和QJsonObject的相互转化