Subsets II

Link: https://leetcode.com/problems/subsets-ii/

Constaint:

The array may contains duplicate.
The array may not be sorted.

Idea

The idea is to think about how to avoid adding duplicate values to the subset. We will process the first occurance of a number (nums[i]) as it is in Subsets I problem, but all the subsequent occurances j, where j > i && nums[j] == nums[i], will be skipped if nums[i] is absent from the subset. Or put it another way, given an array [a, b, b', c], we don't add b' to the subset if: (b = b' && b is NOT in the subset).

class Solution {
    public List<List<Integer>> subsetsWithDup(int[] nums) {
        List<List<Integer>> results = new ArrayList<>();
        Arrays.sort(nums);
        search(nums, 0, new ArrayList<Integer>(), results);
        return results;
    }
    
    private void search(int[] nums, int index, List<Integer> subset, List<List<Integer>> results) {
        if (nums.length == index) {
            results.add(new ArrayList<Integer>(subset));
            return;
        }
        
        subset.add(nums[index]);
        search(nums, index + 1, subset, results);
        subset.remove(subset.size() - 1);
        while (index + 1 < nums.length && nums[index] == nums[index + 1] ) {
            index++;
        }
        
        search(nums, index + 1, subset, results);
    }
}

Subsets II

Reference: https://leetcode.com/problems/subsets-ii/discuss/30150/Very-simple-and-fast-java-solution

上一篇:集合遍历(子集遍历)--二进制


下一篇:未标注目标语料是否均适合用于跨语言学习?『基于对抗判别器高效利用未标注语料的跨语言NER算法AdvPicker』