An intuitive recursion solution


  • 0
    R
    public class Solution {
    
    public List<String> paren = new ArrayList<String>();
    public String lparen = "(";
    public String rparen = ")";
    
    public void genParen(int n, String prefix, int lparenNum, int rparenNum){
        
       if(lparenNum == n && rparenNum == n){
            paren.add(prefix);
            return;
       }
       
       if(lparenNum == 0 || lparenNum == rparenNum){
            genParen(n, prefix + lparen, ++lparenNum, rparenNum);
       
       }else if(lparenNum == n && rparenNum < n){
           genParen(n, prefix + rparen, lparenNum, ++rparenNum);
       
       }else if(lparenNum > rparenNum){
            int templ = lparenNum;
            genParen(n, prefix + lparen, ++lparenNum, rparenNum);
            genParen(n, prefix + rparen, templ, ++rparenNum);
            
       }
    }
    
    public List<String> generateParenthesis(int n) {
        
        genParen(n, "", 0, 0);
        return paren;
        
    }
    

    }


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.