Leetcode 22.生成括号对数

生成括号对数

给出 n 代表生成括号的对数,请你写出一个函数,使其能够生成所有可能的并且有效的括号组合。

例如,给出 n =3,生成结果为:

[

"((()))",

"(()())",

"(())()",

"()(())",

"()()()"

]

 1 class Solution {
 2     public List<String> generateParenthesis(int n) {
 3         List<String> combinations = new ArrayList();
 4         generateAll(new char[2 * n], 0, combinations);
 5         return combinations;
 6     }
 7 
 8     public void generateAll(char[] current, int pos, List<String> result) {
 9         if (pos == current.length) {
10             if (valid(current))
11                 result.add(new String(current));
12         } else {
13             current[pos] = '(';
14             generateAll(current, pos+1, result);
15             current[pos] = ')';
16             generateAll(current, pos+1, result);
17         }
18     }
19 
20     public boolean valid(char[] current) {
21         int balance = 0;
22         for (char c: current) {
23             if (c == '(') balance++;
24             else balance--;
25             if (balance < 0) return false;
26         }
27         return (balance == 0);
28     }
29 }

 1 class Solution {
 2     public List<String> generateParenthesis(int n) {
 3         List<String> ans = new ArrayList();
 4         backtrack(ans, "", 0, 0, n);
 5         return ans;
 6     }
 7 
 8     public void backtrack(List<String> ans, String cur, int open, int close, int max){
 9         if (cur.length() == max * 2) {
10             ans.add(cur);
11             return;
12         }
13 
14         if (open < max)
15             backtrack(ans, cur+"(", open+1, close, max);
16         if (close < open)
17             backtrack(ans, cur+")", open, close+1, max);
18     }
19 }

猜你喜欢

转载自www.cnblogs.com/kexinxin/p/10162977.html
今日推荐