Wednesday, June 24, 2015

Subsets II | Leetcode

Given a collection of integers that might contain duplicates, nums, 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 nums = [1,2,2], a solution is:
[
  [2],
  [1],
  [1,2,2],
  [2,2],
  [1,2],
  []
]
---

Solution: Same algorithm as finding all subsets (combinations), except that we add a duplicate check. We do this by maintaining a Set of Strings. Each possible list in the combinations is conveniently converted to string using List.toString().
public class Solution {
    public List<List<Integer>> subsetsWithDup(int[] nums) {
        List<List<Integer>> answer = new ArrayList<>();
        Set<String> seen = new HashSet<>();
        List<Integer> list = new ArrayList<>(nums.length);
        Arrays.sort(nums);
        subsetsWithDup(nums, answer, list, seen, 0);
        return answer;
    }
    
    private void subsetsWithDup(int[] nums, List<List<Integer>> answer,
            List<Integer> list, Set<String> seen, int start) {
        String s = list.toString();
        if (!seen.contains(s)) {
            answer.add(new ArrayList<Integer>(list));
            seen.add(s);
        }
        if (start == nums.length) return;
        for (int i = start; i < nums.length; i++) {
            list.add(nums[i]);
            subsetsWithDup(nums, answer, list, seen, i + 1);
            list.remove(list.size() - 1);
        }
    }
}

No comments: