Generate Parentheses 解答

Question

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 1

Two conditions to check:

if remained left '(' nums < remained right ')', for next char, we can put '(' or ')'.

if remained left '(' nums = remained right ')', for next char, we can only put '('.

Draw out the solution tree, and do DFS.

 1 public class Solution {
 2     public List<String> generateParenthesis(int n) {
 3         List<String> result = new ArrayList<String>();
 4         List<Character> list = new ArrayList<Character>();
 5         dfs(n, n, list, result);
 6         return result;
 7     }
 8     
 9     private void dfs(int leftRemain, int rightRemain, List<Character> list, List<String> result) {
10         if (leftRemain < 0 || rightRemain < 0 || leftRemain > rightRemain)
11             return;
12         
13         if (leftRemain == 0 && rightRemain == 0) {
14             int size = list.size();
15             StringBuilder sb = new StringBuilder(size);
16             for (char tmpChar : list)
17                 sb.append(tmpChar);
18             result.add(sb.toString());
19             return;
20         }
21         
22         if (leftRemain == rightRemain) {
23             list.add('(');
24             dfs(leftRemain - 1, rightRemain, list, result);
25             list.remove(list.size() - 1);
26         } else {
27             list.add(')');
28             dfs(leftRemain, rightRemain - 1, list, result);
29             list.remove(list.size() - 1);
30             list.add('(');
31             dfs(leftRemain - 1, rightRemain, list, result);
32             list.remove(list.size() - 1);
33         }
34     }
35 }

Solution 2

A much simpler solution.

 1 public class Solution {
 2     public List<String> generateParenthesis(int n) {
 3         List<String> result = new ArrayList<String>();
 4         List<Character> list = new ArrayList<Character>();
 5         dfs(n, n, "", result);
 6         return result;
 7     }
 8     
 9     private void dfs(int leftRemain, int rightRemain, String prefix, List<String> result) {
10         if (leftRemain < 0 || rightRemain < 0 || leftRemain > rightRemain)
11             return;
12         if (leftRemain == 0 && rightRemain == 0) {
13             result.add(new String(prefix));
14             return;
15         }
16         if (leftRemain > 0)
17             dfs(leftRemain - 1, rightRemain, prefix + "(", result);
18         if (rightRemain > 0)
19             dfs(leftRemain, rightRemain - 1, prefix + ")", result);
20     }
21 }
原文地址:https://www.cnblogs.com/ireneyanglan/p/4888754.html