Just like Subsets, this question is a classic NP problem-evaluate a subset. A little more complicated than Subsets is that duplicate elements may appear in the set here, so we should avoid duplicate Subsets when evaluating Subsets. Each time we add an element to Subsets, the original subset is added to this element and then added to the result set. In this way, duplicate elements will generate duplicate Subsets. To avoid such duplication, you need to use a small trick.
In fact, it is relatively simple, that is, whenever we encounter repeated elements, we only add the second half of the current result set to the result set with the current element, because the second half is all the subsets of the element added in the previous step. This element has been added in the previous step, and the first half will be repeated if it is added. Therefore, the complexity of the algorithm is not improved, but some operations are missing, that is, less than half of the repetition. However, we need to sort the Element Set first. Otherwise, it is difficult to judge the duplicate element. Recursive and non-recursive solutions can also be used, but the processing of repeated elements is the same. The recursive code is as follows:
public ArrayList> subsetsWithDup(int[] num) { if(num == null) return null; Arrays.sort(num); ArrayList
lastSize = new ArrayList
(); lastSize.add(0); return helper(num, num.length-1, lastSize);}private ArrayList> helper(int[] num, int index, ArrayList
lastSize){ if(index == -1) { ArrayList> res = new ArrayList>(); ArrayList
elem = new ArrayList
(); res.add(elem); return res; } ArrayList> res = helper(num,index-1,lastSize); int size = res.size(); int start = 0; if(index>0 && num[index]==num[index-1]) start = lastSize.get(0); for(int i=start;i
elem = new ArrayList
(res.get(i)); elem.add(num[index]); res.add(elem); } lastSize.set(0,size); return res;}
The non-recursive code is as follows:
Public ArrayList> subsetsWithDup (int [] num) {ArrayList> res = new ArrayList> (); res. add (new ArrayList
(); If (num = null | num. length = 0) return res; Arrays. sort (num); int start = 0; for (int I = 0; I
NewItem = new ArrayList
(Res. get (j); newItem. add (num [I]); res. add (newItem);} if (I
Repeat processing of such NP problems occurs frequently in LeetCode, for example, Permutations II. In fact, the essence is to ignore the results of the previous element when a repeating element comes in, only new results generated by repeated elements are considered.