LeetCode - Generate Parentheses

本文介绍了一种生成合法括号组合的算法,通过递归深度优先搜索遍历所有可能的序列,确保左括号数量始终不大于右括号数量,避免出现非法序列。给出的代码实现了这一逻辑,并分析了时间复杂度。

Generate Parentheses

2013.12.7 00:49

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:

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

Solution:

  If you're familiar with the Catalan Numbers, you'll see it's a typical solution for this problem.

  Since all the combinations are required, we'll use DFS to go through every possible sequence.

  Let's consider the recursion in the following way:

    1. For a sequence of length 2 * n, there're n '(' and n ')'

    2. For a valid sequence, number of '(' will never be less than the number of ')' at any position. If there're more ')' than '(', there must be a mismatch.

    3. Always do the recursion from left to right.

  Time complexity is H(n) * O(n) = C(2 * n, n) / (n + 1) * n, that's roughly O(n!). Space complexity is not sure yet...

Accepted code:

 1 // 1AC, simple recursion will do, but keep your mind clear or it's easy to get things complicated
 2 class Solution {
 3 public:
 4     vector<string> generateParenthesis(int n) {
 5         // IMPORTANT: Please reset any member data you declared, as
 6         // the same Solution instance will be reused for each test case.
 7         result.clear();
 8         
 9         dfs(n, n, "");
10         
11         return result;
12     }
13 private:
14     vector<string> result;
15     
16     void dfs(int cl, int cr, string pat) {
17         if(cl == 0 && cr == 0){
18             result.push_back(pat);
19         }
20         
21         int i;
22         if(cl < cr){
23             if(cl > 0){
24                 dfs(cl - 1, cr, pat + "(");
25             }
26             if(cr > 0){
27                 dfs(cl, cr - 1, pat + ")");
28             }
29         }else if(cl == cr){
30             if(cl > 0){
31                 dfs(cl - 1, cr, pat + "(");
32             }
33         }else{
34             return;
35         }
36     }
37 };

 

转载于:https://www.cnblogs.com/zhuli19901106/p/3462373.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值