Generate Parentheses
2015-11-28 20:57
260 查看
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:
For example, given n = 3, a solution set is:
"((()))", "(()())", "(())()", "()(())", "()()()"
#include <vector> #include <string> using namespace std; class Solution { public: vector<string> generateParenthesis(int n) { vector<string> result; vector<bool> path; dfs(0,0,0,path,result,n); return result; } private: void dfs(int curr,int r,int l,vector<bool>& path, vector<string>& result,int n){ if(curr == 2*n){ string s; for(int i=0;i<2*n;i++){ if(path[i]==true){ s.push_back('('); }else s.push_back(')'); } result.push_back(s); return; } if(r==l){ path.push_back(true); dfs(curr+1,r+1,l,path,result,n); path.pop_back(); }else if(r>l && r<n){ path.push_back(true); dfs(curr+1, r+1, l, path, result, n); path.pop_back(); path.push_back(false); dfs(curr+1, r, l+1, path, result, n); path.pop_back(); }else{ path.push_back(false); dfs(curr+1,r,l+1,path,result,n); path.pop_back(); } } }; int main() { Solution s; vector<string> result; result = s.generateParenthesis(3); return 0; }
相关文章推荐
- 大话设计模式之面向对象基础篇(二)
- WiFi P2P抓包分析(二) P2P组网
- C#程序从Excel表格中读取数据并进行处理
- [总结]视音频编解码技术零基础学习方法
- 针对xss漏洞的一些方法
- 集合框架Map笔记持续
- thinkphp 3.2 实现登录功能+验证码
- 我在mac os上安装gopherjs的过程
- OC总结
- Java注释
- JS - 按钮倒计时
- 【LeetCode从零单刷】Kth Largest Element in an Array
- 基于WebRTC的多人视频会议
- 【小程序】统计字符
- iOS笔记--oc语法7 (深、浅复制的基本概念)
- 【Ubuntu下安装配置】右键终端、google-chrome安装、sogou拼音安装
- 关于hadoop 配置文件的一些实验
- CSS Page Layout: Building Float-Based Layouts
- 简洁和高效是我们永恒的眷恋
- n波那契