Thursday, March 6, 2014

Leetcode: Subsets II



Given a collection of integers that might contain duplicates, S, return all possible subsets.
Note:
  • Elements in a subset must be in non-descending order.
  • The solution set must not contain duplicate subsets.
For example,
If S = [1,2,2], a solution is:
[
  [2],
  [1],
  [1,2,2],
  [2,2],
  [1,2],
  []
]

Solution:

public class Solution {
    public List<List<Integer>> subsetsWithDup(int[] num) {
        Arrays.sort(num);
        List<List<Integer>> solution = new ArrayList<List<Integer>>();
        subsetsWithDup(num, 0, new ArrayList<Integer>(), solution);
        return solution;
    }
    
    public void subsetsWithDup(int[] num, int index, ArrayList<Integer> tempSolution, List<List<Integer>> solution) {
        if(index == num.length)
        {
            solution.add((List<Integer>)tempSolution.clone());
            return;
        }
        
        //Do not add element num[i]
        int value = num[index];
        int i= index;
        while(i<num.length && num[i]==value)
            i++;
        subsetsWithDup(num, i, tempSolution, solution);
            
        //Add element num[i]
        tempSolution.add(num[index]);
        subsetsWithDup(num, index+1, tempSolution, solution);
        tempSolution.remove(tempSolution.size()-1);
    }
}

No comments :

Post a Comment