[LeetCode] 22. Generate Parentheses



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

The solution to this problem can be represented as a tree, therefore, we should use backtracking to iterate all possibility while trimming down those unqualified one.

                0
                |
               '('
          /           \
       '(('           '()'
     /     \           |
  '((('    '(()'     '()('

   ...      ...       ...

The code is shown as below.

Java

public class Solution {
   public List generateParenthesis(int n) {
       
       List ans = new ArrayList();
       
       if(n<=0)    return ans;
       
       backtrack(ans,"",0,0,n);
       return ans;
   }
   
   public void backtrack(List ans, String subans, int left_num, int right_num, int max){
       
       // Reach the bottom of the tree 
       if(subans.length() == max*2 && left_num == max && right_num ==max){
           ans.add(subans);
           return;
       }   
       
       //First adding '('
       if(left_numright_num){
           backtrack(ans,subans+")",left_num,right_num+1,max);
       }
   }
}

From the code, we can see that the sequence of two if-sentence is pretty important, as we should first adding '(' rather than randomly adding ')' in order to keep the parentheses valid.


你可能感兴趣的:([LeetCode] 22. Generate Parentheses)