首页 > 其他 > 详细

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

时间:2015-04-03 14:45:07      阅读:289      评论:0      收藏:0      [点我收藏+]

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         }

 

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

原文:http://www.cnblogs.com/amethystltt/p/4389769.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!