Compared with the previous Subsets, HashSet is used as a natural filter.
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], a solution is: [[2], [1], [1, 2], [2, 2], [1, 2], [] **/public class S90 {public static void main (String [] args) {int [] num = {1, 2}; System. out. println (subsetsWithDup (num);} // use HashSet to filter out public static ArrayList <Integer> subsetsWithDup (int [] num) {int len = num. length; Set <ArrayList <Integer> set = new HashSet <ArrayList <Integer> (); Arrays. sort (num); // calculate all subsets by using the bits corresponding to the binary system. In the binary system, 0 indicates no, and 1 indicates for (int I = 0; I <Math. pow (2, len); I ++) {ArrayList <Integer> list = new ArrayList <Integer> (); int tmp = I; // The number of len pairs, check whether the rightmost bits are for (int j = 0; j <len; j ++) {int bit = tmp & 1; tmp >>=1; if (bit = 1) {list. add (num [j]) ;}} set. add (list);} return new ArrayList <Integer> (set );}}