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:
"((()))", "(()())", "(())()", "()(())", "()()()"
Solution in Java:
public class Solution {
public List<String> generateParenthesis(int n) {
List<String> resl = new ArrayList<String>();
if(n==0) return resl;
generate(n, n, resl, "");
return resl;
}
public void generate(int left, int right, List<String> result, String currentResult){
if(left==0&&right ==0) result.add(currentResult);
if(left>0) generate(left-1, right, result, currentResult+"(");
if(right>0&&left<right) generate(left, right-1, result, currentResult+")");
}
}
Note:
该问题和《编程之美》的买票找零问题一样,通过买票找零问题我们可以知道,针对一个长度为2n的合法排列,第1到2n个位置都满足如下规则:左括号的个数大于等于右括号的个数。所以,我们就可以按照这个规则去打印括号:假设在位置k我们还剩余left个左括号和right个右括号,如果left>0,则我们可以直接打印左括号,而不违背规则。能否打印右括号,我们还必须验证left和right的值是否满足规则,如果left>=right,则我们不能打印右括号,因为打印会违背合法排列的规则,否则可以打印右括号。如果left和right均为零,则说明我们已经完成一个合法排列,可以将其打印出来。通过深搜,我们可以很快地解决问题,针对n=2,问题的解空间如下:
Reference:http://blog.csdn.net/yutianzuijin/article/details/13161721

本文介绍了一个生成所有合法括号组合的算法实现。对于给定的正整数n,该算法能够生成所有可能的且语法正确的2n长度的括号字符串。通过递归的方式,确保在任一位置左括号的数量都不小于右括号的数量。

2474

被折叠的 条评论
为什么被折叠?



