Subsets II(lintcode 18)

Description

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

Notice:

* Each element in a subset must be in non-descending order.
* The ordering between two subsets is free.
* 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],
  []
]

Interface

class Solution {
    /**
     * @param nums: A set of numbers.
     * @return: A list of lists. All valid subsets.
     */
    public ArrayList<ArrayList<Integer>> subsetsWithDup(int[] nums) {
        // write your code here

    }
}

Solution

class Solution {
    /**
     * @param nums: A set of numbers.
     * @return: A list of lists. All valid subsets.
     */
    public ArrayList<ArrayList<Integer>> subsetsWithDup(int[] nums) {
        // write your code here
        ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();
        if (nums == null || nums.length == 0) {
            return result;
        }

        Arrays.sort(nums);
        ArrayList<Integer> list = new ArrayList<Integer>();
        helper(result, list, nums, 0);
        return result;
    }

    private void helper(ArrayList<ArrayList<Integer>> result, ArrayList<Integer> list, int[] nums, int len) {
        result.add(new ArrayList<Integer>(list));
        for (int i = len; i < nums.length; ++i) {
            if (i != len && nums[i] == nums[i - 1]) {
                continue;
            }

            list.add(nums[i]);
            helper(result, list, nums, i + 1);
            list.remove(list.size() - 1);
        }
    }
}

results matching ""

    No results matching ""