Generate Parentheses
Given n pairsof parentheses, write a function to generate all combinations of well-formedparentheses.
For example, given n = 3, a solution set is:
"((()))", "(()())","(())()", "()(())", "()()()"
【分析-非原创】下面的代码是参考中提供的,我已经看醉了。leftNum表示剩余的左括号,rightNum表示剩余的右括号,如果rightNum不为0,表明可以往下继续递归;rightNum不为0且rightNum大于leftNum,表明剩余的右括号多于剩余的左括号,此时可以添加右括号。
参考:http://blog.csdn.net/yutianzuijin/article/details/13161721
/**
* 创建时间:2014年9月21日下午5:16:24 项目名称:Test
*
* @author Cao Yanfeng
* @since JDK 1.6.0_21 类说明: n对括号的合法排列
*/
public class GenerateParenthesesTest {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated methodstub
List<String> result = generateParentheses(2);
for (String string : result) {
System.out.println(string);
}
}
public static List<String>generateParentheses(int pairs) {
List<String> result = newArrayList<String>();
generate(pairs, pairs, "", result);
return result;
}
public static void generate(int leftNum, int rightNum, String s,
List<String> result) {
if (leftNum == 0 && rightNum == 0) {
result.add(s);
}
if (leftNum > 0) {
generate(leftNum - 1, rightNum, s + '(', result);
}
if (rightNum > 0 && leftNum < rightNum) {
generate(leftNum, rightNum - 1, s + ')', result);
}
}
}