LeetCode-Generate Parentheses

本文介绍了一个使用递归方法生成所有有效的括号组合的算法。给定一个正整数 n,该算法将生成所有可能的由 n 对括号组成的且合法的括号字符串。通过递归调用,在每一步中选择添加左括号或右括号,确保任何时候右括号的数量不会超过左括号。

题目:

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 };

 

转载于:https://www.cnblogs.com/sixue/p/4008438.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值