Java Solution using Stack


  • 0
    E
    public class Solution {
        public List<String> generateParenthesis(int n) {
            
            PStack s=new PStack();
            List<String> res=new ArrayList<String>();
            s.push(new PStr("(",1,0));
    
            while(s.size>0){
                PStr cur=s.pop();
                if(cur.open<n){
                    if(cur.open==cur.close){
                        s.push(new PStr(cur.str+"(",cur.open+1,cur.close));
                    }
                    else{
                        s.push(new PStr(cur.str+"(",cur.open+1,cur.close));
                        s.push(new PStr(cur.str+")",cur.open,cur.close+1));
                    }
                }
                else{
                    while(cur.close<n){
                        cur.str=cur.str+")";
                        cur.close++;
                    }
                    res.add(cur.str);
                }
            }
            return res;
        }
    }
    
    class PStr{
        String str;
        int open;
        int close;
        
        PStr(String s, int o, int c){
            str=s;
            open=o;
            close=c;
        }
    }

Log in to reply
 

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