AC java solution with iteration and StringBuilder


  • 1
    J
    public List<String> generateParenthesis(int n) {
            List<StringBuilder> list = new ArrayList<>();
            list.add((new StringBuilder()).append('(').append(1));
            for(int i=1;i<2*n;i++){
                for(int j=list.size()-1;j>=0;j--){
                    StringBuilder temp = list.get(j);
                    int leftnum = temp.charAt(i)-'0';
                    list.remove(j);
                    if(leftnum<2*n-i){
                        StringBuilder temp1 = new StringBuilder(temp);
                        temp1.insert(i,'(').setCharAt(i+1,(char)(leftnum+1+'0'));
                        list.add(temp1);
                    }
                    if(leftnum>0){
                        StringBuilder temp1 = new StringBuilder(temp);
                        temp1.insert(i,')').setCharAt(i+1,(char)(leftnum-1+'0'));
                        list.add(temp1);
                    }
                }
            }
            List<String> res = new ArrayList<>();
            for(StringBuilder sb: list) res.add(sb.deleteCharAt(2*n).toString());
            return res;
        }
    

    I stored a variable of number of left parenthesis '(' minus right parenthesis ')' as the last char in each StringBuilder.


Log in to reply
 

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