question
Given a list of numbers to has duplicate numbers, return all possible subsets.
Example
If S = [1,2,2], a solution is:
[[2],
[1],
[1,2,2],
[2,2],
[1,2],
[] ]
Challenge
Can you did it in both recursively and iteratively? Solution
Recursion: Similar to subsets 17, but because there are duplicate elements, there are several points to be aware of in order to avoid duplicate solutions.
1 Put all the repeating elements together so that the input array is sorted first
2 The method of avoiding repetition is that the repeating element can only take the first element, so before adding an element, determine whether the element value is equal to the previous element.
Non-recursion:
The code is as follows:
Recursion:
Class Solution {public list<list<integer>> subsetswithdup (int[] nums) {LIST<LIST<INTEGER&G
t;> result = new arraylist<> ();
list<integer> list = new arraylist<> ();
if (nums = null | | nums.length = = 0) {return result;}
Arrays.sort (Nums);
Helper (result, list, nums, 0);
return result;
public void Helper (list<list<integer>> result, list<integer> List, int []nums, int index) {
if (!result.contains (list)) {Result.add (new arraylist<> (list));}
Result.add (new arraylist<> (list));
for (int i = index; i < nums.length; i++) {List.add (nums[i));
Helper (result, list, nums, i+1);
List.remove (List.size ()-1); }
}
}