Simple Java Solution. Beats 91.76% of submissions


  • 0
    D

    public class Solution {
    public List<String> generateParenthesis(int n) {
    List<String> res = new ArrayList<String>();
    char[] currStr= new char[2*n];
    generateParanthesis(res,currStr,0,0,0,n);
    return res;

    }
    
    void generateParanthesis(List<String> res,char[] currStr, int openCount, int closeCount, int index, int n){
        if(openCount==n && closeCount==n){
            res.add(new String(currStr));
            currStr = new char[2*n];
            return;
        }
        
        if(openCount<n){
            currStr[index]='(';
            generateParanthesis(res,currStr,openCount+1,closeCount,index+1,n);
        }
        if(closeCount<openCount){
            currStr[index]=')';
            generateParanthesis(res,currStr,openCount,closeCount+1,index+1,n);
            
        }
        
    }
    

    }


Log in to reply
 

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