标签:
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 }
标签:
原文地址:http://www.cnblogs.com/amethystltt/p/4389769.html