My short recursive java solution


  • 0
    L

    Hope this helps!

    public class Solution {

    List answers = new ArrayList<ArrayList<Integer>>();
    int[] num;
    
    public List<List<Integer>> subsetsWithDup(int[] num) {
        Arrays.sort( num );
        this.num = num;
        
        helper( 0, new LinkedList<Integer>() );
        return answers;
    }
    /*
    if num = (1,1);
    index: 0 | 1 | 2
    []    +#  +# = []
              +1 = [1]
          +1  +# = [1] ( skip** )
              +1 = [1,1]
    */
    
    public void helper( int index, LinkedList curr ){
        if( index >= num.length ){
            answers.add( curr );
            return;
        }
        
        //Not including this number from this index
        //**If this number is the same as last number, skip this step.
        //Ex: skipping [1, #] since we already have [#,1].
        if( (curr.size() != 0 && (int) curr.getLast() != num[index] ) || ( curr.size() == 0 ) )
            helper( index+1, (LinkedList) curr.clone() ); 
        
        //include this number [1]->[1,1]
        curr.add( num[ index ] );
        helper( index+1, (LinkedList) curr.clone() );
    }
    

    }


Log in to reply
 

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