Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.spa
For example, given n = 3, a solution set is:code
"((()))", "(()())", "(())()", "()(())", "()()()"
orm
给定变量n,表示有n对括号,输出n对括号全部正确匹配的状况。blog
用递归来实现,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 + ")"); } } }