[leet code] 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],
  []
]
========

Analysis:

Idea is the same as [leet code] Subsets, except this time we need to deal with the duplicate element case.

Solution for the duplicate element case is that when we are choosing the current element of a subset, we skip the duplicated choices.  For example, when we are constructing an subset which length = 2 (S = [1,2,3]), we try only number 1 and 2 for the 1st element.

public class Solution {
    public ArrayList<ArrayList<Integer>> subsetsWithDup(int[] num) {
        ArrayList<ArrayList<Integer>> rs = new ArrayList<ArrayList<Integer>>();
        Arrays.sort(num); // for test case
        
        for(int length=0; length<=num.length; length++) // different length of subsets
        // use one array list to compute all the possible subsets at certain length
        helper(num, rs, new ArrayList<Integer>(), length, 0);  
        return rs;
    }
    
    public void helper(int[] num, ArrayList<ArrayList<Integer>> rs, ArrayList<Integer> subSet, int length, int startPoint){
        if(length == subSet.size()){// one possible subset constructed
            rs.add(new ArrayList<Integer>(subSet));
        }
        else{ 
            for(int i=startPoint; i<num.length; i++){// switch current element
                subSet.add(num[i]);
                helper(num, rs,subSet, length, i+1); // throw the remaining elements to recursive call
                subSet.remove(subSet.size()-1); // remove the current element and try the next element
                // only non-duplicate element would be chosen as current element
                while (i<num.length-1 && num[i+1] == num[i]) i++; 
            }
        }
    }
}



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章