22_Generate Parentheses
2016-04-20 16:42 FTD_W 阅读(119) 评论(0) 编辑 收藏 举报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:
"((()))", "(()())", "(())()", "()(())", "()()()"
给定变量n,表示有n对括号,输出n对括号所有正确匹配的情况。
用递归来实现,left和right表示左右括号各剩下多少个,left >= right,即左括号剩下的多,则不能插入右括号。
public class Solution { private List<string> result = new List<string>(); public IList<string> GenerateParenthesis(int n) { string current = ""; generate(n, n, current); return result; } public void generate(int left, int right, string current)//left 和 right 表示还剩下的左右括号的个数 { if(left == 0 && right == 0) { result.Add(current); return; } if(left > 0) { generate(left - 1, right, current + "("); } if(right > 0 && left < right) { generate(left, right - 1, current + ")"); } } }