My recursion code


  • 0
    C
    public class Solution {
    public List<String> ret=new ArrayList<String> ();
    
    public void getResult(String preStr,boolean isLeft,int leftNum,int rightNum){
        if(isLeft) leftNum--;
        else rightNum--;
    
        if(leftNum<0||rightNum<0||rightNum<leftNum){
            if(isLeft) leftNum++;
            else rightNum++;
            return;
        }else{
            String tmpStr="";
            if(isLeft) tmpStr=preStr+"(";
            else tmpStr=preStr+")";
    
            if(rightNum==0){
                ret.add(tmpStr);
                return;
            }else{
                getResult(tmpStr,true,leftNum,rightNum);
                getResult(tmpStr,false,leftNum,rightNum);
            }
        }
    }
    
    public List<String> generateParenthesis(int n) {
        getResult("",true,n,n);
        return ret;
    }
    

    }


Log in to reply
 

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