Simple Java recursion code!


  • 0
    J
    StringBuilder sb = new StringBuilder("(");
    public List<String> generateParenthesis(int n) {
            List<String> rst = new LinkedList<String>();
            combination(n-1,n,sb,rst);
            return rst;
        }
    public void combination(int left,int right,StringBuilder sb,List<String> rst){
            if(left==0&&right==0){
                rst.add(sb.toString());
            }
            if(left>0){
                combination(left-1,right,sb.append("("),rst);
                sb.deleteCharAt(sb.length()-1);
            }
            if(right>left){
                combination(left,right-1,sb.append(")"),rst);
                sb.deleteCharAt(sb.length()-1);
            }
        }
    }

Log in to reply
 

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