CC9.6 (LeetCode-Generate Parentheses ) Implement analgorithm to print all valid combinations of n-pa...

Implement analgorithm to print all valid combinations of n-pairs of parenthese.

Analysis:

-只要待加入的有左括号就可以加入左括号。最初可以加入的左括号为n个。

-只要已加入的左括号比右括号多就可以加入右括号。最初可以加入的右括号为0个。每加入一个左括号就可以多加入一个右括号。

-递归

Note:

- string c 不能用string builder代替,递归之后没有clean, 结果被叠加变成((()))(()())...

 1 public static List<string> GenerateParenthesis(int n)
 2         {
 3             List<string> result = new List<string>();
 4             string c = string.Empty;
 5             GenerateParenthesis(n, 0, c, result);
 6             return result;
 7         }
 8 
 9         public static void GenerateParenthesis(int left, int right, string c, List<string> list)
10         {
11             if (list == null)
12             {
13                 return;
14             }
15 
16             if (left == 0 && right == 0)
17             {
18                 list.Add(c);
19                 return;
20             }
21 
22             if (left > 0)
23             {
24                 GenerateParenthesis(left - 1, right + 1, c + "(", list);
25             }
26 
27             if (right > 0)
28             {
29                 GenerateParenthesis(left, right - 1, c + ")", list);
30             }
31         }

 

转载于:https://www.cnblogs.com/amethystltt/p/4389769.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值