与之前的Subsets题相比,改用HashSet来作为天然的过滤。
package Level4;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
/**
* Subsets II
*
* 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],
[]
]
*
*/
public class S90 {
public static void main(String[] args) {
int[] num = {1,2,2};
System.out.println(subsetsWithDup(num));
}
// 与之前相比改用HashSet来过滤
public static ArrayList
> subsetsWithDup(int[] num) {
int len = num.length;
Set> set = new HashSet>();
Arrays.sort(num);
// 利用2进制对应的bit来求所有subset,2进制中,0代表不选,1代表选择
for(int i=0; i list = new ArrayList();
int tmp = i;
// 对长为len的数,循环检查最右位是否为一
for(int j=0; j>= 1;
if(bit == 1){
list.add(num[j]);
}
}
set.add(list);
}
return new ArrayList>(set);
}
}