My easy-to-understand java solution (Do it Iteratively)


  • 0
    G
    public List<String> generateParenthesis(int n) {
            List<String> list = new ArrayList<String>();
            if(n== 0){  return list;}
            List<Integer> left = new ArrayList<Integer>();
            List<Integer> right = new ArrayList<Integer>();
            list.add("(");
            left.add(1);
            right.add(0);
            
            for(int i=2; i<=2*n; i++){
                for(int j=0; j<list.size(); j++){
                    int lnum= left.get(j);
                    int rnum= right.get(j);
                    String tmp = list.get(j);
                    if(lnum< n){
                        String t = tmp + "(";
                        list.set(j, t);
                        left.set(j,lnum+1);
                    }
                    if(rnum<lnum){
                        String t = tmp +")";
                        if(lnum<n){
                            list.add(t);
                            left.add(lnum);
                            right.add(rnum+1);
                            
                        }else{
                            list.set(j, t);
                            right.set(j, rnum+1);
                        }
                    }
                }
            }
            return list;
        }

Log in to reply
 

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