您的位置:首页 > 其它

LeetCode 22 Generate Parentheses

2017-07-01 12:04 459 查看
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对括号有多少种合法组合方式。

依然是回溯法,当当前组合不合法的时候退出,怎么判断是否合法呢?从起点到任意一个位置的左括号数量一定大于等于右括号,否则非法。

举例1 ((()),至少当前为止还是合法的,因为再加一个右括号就完美了

举例2 (()))这个一定非法,无论在怎么加。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

public static List<string> generateParenthesis(int n) {
List</string><string> list = new ArrayList</string><string>();
search("", n, n, list);
return list;
}
 
public static void search(String add, int left, int right, List</string><string> list) {
if (left < 0 || right < 0 || left > right)
return;
if (left == 0 && right == 0) {
list.add(add);
return;
}
search(add + "(", left - 1, right, list);
search(add + ")", left, right - 1, list);
}

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