您的位置:首页 > 其它

【LeetCode题目记录-12】所有合法的括号序列

2014-09-22 21:58 323 查看

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,表明剩余的右括号多于剩余的左括号,此时可以添加右括号。

参考:/article/1536794.html

/**
* 创建时间: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);
}
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: