Given a collection of integers that might contain duplicates, S, 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 S = [1,2,2],
a solution is:
[ [2], [1], [1,2,2], [2,2], [1,2], [] ]There is a simpler version, where no duplicates are allowed.
10/31
Algorithm:
take S1 = [1,1,2,2,2,3] for example
start from the list { [ ] }, in order to be more clear, use { } for the outer layer of list
keep a variable as care which remembers from where the last time elements are added in.
start from { [ ] }
- consider 1:
{ [ ] , [1] } , care = 1
- consider 1:
only add from care = 1 to the end
{ [ ] , [1], [1,1]}, care = 2
- consider 2
because this is the first time that 2 showed up in the list, simply scan from the head of the list to the end, and add 2 to each of the sublist
{ [ ], [1], [1,1], [2], [1,2], [1,1,2] }, care = 3
- consider 2 again
this time 2 has shown before, so just scan from care to the end, adding 2 to each sublist
{[ ], [1], [1,1], [2], [1,2], [1,1,2] , [2,2], [1,2,2], [1,1,2 ,2] }, now care = 6
- consider 3
this is the first time that 3 shows up, so append 3 to each of the sublist and add to the list
public class Solution {
public List<List<Integer>> subsetsWithDup(int[] S) {
Arrays.sort(S); //err1: remember to sort
int len = S.length;
List<List<Integer>> list = new ArrayList<List<Integer>>();
list.add(new ArrayList<Integer>());
int care = 0;
for(int i = 0; i<len; i++){
int size = list.size();
if(i > 0 && S[i] == S[i-1]){
for(int j=care; j<size; j++){
List<Integer> newly = new ArrayList<Integer>(list.get(j));
newly.add(S[i]);
list.add(newly);
}
}else{
for(int j=0; j<size; j++){
List<Integer> newly = new ArrayList<Integer>(list.get(j));
newly.add(S[i]);
list.add(newly);
}
}
care = size;
}
return list;
}
}time complexity and space complexity: not polynomial
considering all distinct elements and checking the i-th element, the length of the list is not polynomial, and you have to copy all the list
Note that this problem itself cannot be polynomial.
167

被折叠的 条评论
为什么被折叠?



