LeetCode90(2021.3.31)

LC90. 子集 II

class Solution {
    List<Integer> tmp = new ArrayList<Integer>();
    List<List<Integer>> res = new ArrayList<List<Integer>>();

    public List<List<Integer>> subsetsWithDup(int[] nums) {
        int n = nums.length;
        Arrays.sort(nums);
        for (int mask = 0; mask < (1 << n); ++mask) {
            tmp.clear();
            boolean same = false;
            for (int i = 0; i < n; ++i) {
                if ((mask & (1 << i)) != 0) {
                    if (i > 0 && (mask >> (i - 1) & 1) == 0 && nums[i] == nums[i - 1]) {
                        same = true;
                        break;
                    }
                    tmp.add(nums[i]);
                }
            }
            if (!same) {
                res.add(new ArrayList<Integer>(tmp));
            }
        }
        return res;
    }
}

发表评论