码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode-Generate Parentheses

时间:2014-10-06 20:28:50      阅读:186      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   io   ar   for   sp   div   c   

题目:

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:

"((()))", "(()())", "(())()", "()(())", "()()()"

 

采用递归的方式求解

 1 class Solution{
 2 public:
 3        void generate(vector<string> &res,string curr,int m,int n){
 4                if(m==0 && n==0){ //递归终止条件
 5                    res.push_back(curr);
 6                    return;
 7                }
 8                
 9                if(m!=0) generate(res,curr+"(",m-1,n);
10                
11                if(m<n && n!=0) generate(res,curr+")",m,n-1);
12        }
13        
14        vector<string> generateParenthesis(int n){
15                vector<string> res;
16                res.clear();
17                
18                if(n>0){
19                    generate(res,string(),n,n);
20                }
21                
22                return ret;
23        }
24 };

 

LeetCode-Generate Parentheses

标签:style   blog   color   io   ar   for   sp   div   c   

原文地址:http://www.cnblogs.com/sixue/p/4008438.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!