http://www.lintcode.com/en/problem/subsets-ii/#
this problem we will have met the duplicates in the array input. since we sort the data. that means all the duplicates value will stick to one another. therefore, the way we remove duplicates is to filter out the scenario where we grab the nth appearance a dup value in the case where we skip the (n-1)th appearance of the dup value.
class Solution {
/**
* @param nums: A set of numbers.
* @return: A list of lists. All valid subsets.
*/
public ArrayList<ArrayList<Integer>> subsetsWithDup(int[] nums) {
// write your code here
ArrayList<ArrayList<Integer>> ans = new ArrayList<>();
if (nums == null || nums.length == 0) {
return ans;
}
Arrays.sort(nums);
ArrayList<Integer> cur = new ArrayList<>();
helper(ans, cur, nums, 0);
return ans;
}
private void helper(ArrayList<ArrayList<Integer>> ans,
ArrayList<Integer> cur,
int[] nums,
int startIndex) {
ans.add(new ArrayList<Integer>(cur));
for (int i = startIndex; i < nums.length; i++) {
if ((i - 1) >= 0 && nums[i] == nums[i - 1] && i > startIndex) {
continue;
}
cur.add(nums[i]);
helper(ans, cur, nums, i + 1);
cur.remove(cur.size() - 1);
}
}
}