lintcode18- subsetsII- medium
Given a list of numbers that may has duplicate numbers, return all possible subsets
Notice
- Each element in a subset must be in non-descendingorder.
- 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], []]
Challenge
Can you do it in both recursively and iteratively?
和 I 一样,仅仅加一个判断if,if (i == index || nums[i] != nums[i - 1])才进行递归。
public class Solution { /* * @param nums: A set of numbers. * @return: A list of lists. All valid subsets. */ public List<List<Integer>> subsetsWithDup(int[] nums) { if (nums == null){ return null; } //List<List<Integer>> result = new ArrayList<>(new ArrayList<Integer>()); List<List<Integer>> result = new ArrayList<>(); if (nums.length == 0){ result.add(new ArrayList<Integer>()); return result; } Arrays.sort(nums); helper(new ArrayList<Integer>(), nums, 0, result); return result; } private void helper(List<Integer> subset, int[] nums, int index, List<List<Integer>> result){ result.add(new ArrayList<Integer>(subset)); for (int i = index; i < nums.length; i++){ if (i == index || nums[i] != nums[i - 1]){ subset.add(nums[i]); helper(subset, nums, i + 1, result); subset.remove(subset.size() - 1); } } } }