Subsets

Given a list of numbers that may has duplicate numbers, return all possible subsets

  • Elements in a subset must be in non-descending order.
  • The solution set must not contain duplicate subsets.
  • The solution set must not contain duplicate subsets.

Example:

If S = [1,2,2], a solution is:

[
  [2],
  [1],
  [1,2,2],
  [2,2],
  [1,2],
  []
]

Solution:

We could use depth first to solve it.

Code:

class Solution {

    public ArrayList<ArrayList<Integer>> subsets(int[] nums) {
        ArrayList<ArrayList<Integer>> res = new ArrayList<>();
        if (nums == null || nums.length == 0) {
            return res;
        }
        ArrayList<Integer> path = new ArrayList<>();
        Arrays.sort(nums);
        helper(nums, 0, path, res);
        return res;
    }
    private void helper(int[] nums, int index, ArrayList<Integer> path, 
                            ArrayList<ArrayList<Integer>> res) {
        res.add(new ArrayList<>(path));
        for (int i = index; i < nums.length; i++) {
            if (i != index && nums[i] == nums[i - 1]) {
                continue;
            }
            path.add(nums[i]);
            helper(nums, i + 1, path, res);
            path.remove(path.size() - 1);
        }
    }
}

results matching ""

    No results matching ""