[LeetCode] Generate Parentheses

本文介绍了一种递归算法,用于生成所有可能的有效括号组合。该算法通过递归地添加开括号和闭括号,并确保任何时候闭括号的数量不超过开括号的数量来实现。

Well, there are two ways to add a open or close parenthesis to the current string.

  1. If number of ( is less than n, you can add (;
  2. If number of ) is less than number of (, you can add ).

Maintain a res for all the possible parenthesis and a temporary string sol for the current answer. Now we have the following code.

 1 class Solution {
 2 public:
 3     vector<string> generateParenthesis(int n) {
 4         vector<string> res;
 5         string sol;
 6         genParen(sol, 0, 0, n, res);
 7         return res;
 8     }
 9 private:
10     void genParen(string& sol, int open, int close, int total, vector<string>& res) {
11         if (open == total && close == total) {
12             res.push_back(sol);
13             return;
14         }
15         if (open < total) {
16             sol += '(';
17             genParen(sol, open + 1, close, total, res);
18             sol.resize(sol.length() - 1);
19         }
20         if (close < open) {
21             sol += ')';
22             genParen(sol, open, close + 1, total, res);
23             sol.resize(sol.length() - 1);
24         }
25     }
26 }; 

 

转载于:https://www.cnblogs.com/jcliBlogger/p/4573496.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值