90. Subsets II

题目链接

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

题目描述

Given a collection of integers that might contain duplicates, nums, return all possible subsets (the power set).

Note: The solution set must not contain duplicate subsets.

Example:

Input: [1,2,2]
Output:
[
  [2],
  [1],
  [1,2,2],
  [2,2],
  [1,2],
  []
]

这个题目78. Subsets相似,只是多了重复的元素,因此需要注意,比如[1,2,2],如果我们取下标为0和1的,则组成了列表[1,2],如果取下标我0和2的,则也是[1,2],因此结果会有重复,下边我们还是使用两种方法解决这个问题。

代码一:

class Solution {
    public List<List<Integer>> subsetsWithDup(int[] nums) {
        if(nums == null || nums.length == 0) {
            return new ArrayList<List<Integer>>();
        }
        Arrays.sort(nums);
        List<Integer> list = new ArrayList<>();
        List<List<Integer>> ans = new ArrayList<List<Integer>>();
        int len = nums.length;
        dfs(0, len, ans, list, nums);

        /*for(List<Integer> a : ans) {
            res.add(a);
        }*/
        return ans;
    }

    private void dfs(int index, int len, List<List<Integer>> ans, List<Integer> list, int[] nums) {
        ans.add(new ArrayList<Integer>(list));
        for(int i = index; i < nums.length; i++) {
            if(i > index && nums[i] == nums[i-1]){
                continue;
            }
            list.add(nums[i]);
            dfs(i+1, len, ans, list, nums);
            list.remove(list.size() - 1);
        }
    }
}

代码二:

class Solution {
    public List<List<Integer>> subsetsWithDup(int[] nums) {
        if(nums == null || nums.length == 0) {
            return new ArrayList<List<Integer>>();
        }
        Arrays.sort(nums);

        List<Integer> list = new ArrayList<>();
        int len = nums.length;
        List<List<Integer>> ans = new ArrayList<List<Integer>>();
        dfs(0, len, ans, list, nums);


        return ans;
    }

    private void dfs(int index, int len, List<List<Integer>> ans, List<Integer> list, int[] nums) {
        if(index == len) {
            ans.add(new ArrayList<Integer>(list));
            return;
        }
        int temp = index; 
        while(temp + 1 < len && nums[temp] == nums[temp+1] ) temp++; // temp指向相同数列表的最后一个,比如[1,2,2]中,如果当前index为1,则temp为2
        list.add(nums[index]);
        dfs(index+1, len, ans, list, nums); // 意思是,当前这个元素取了,下个元素我们先不管,注意是index+1
        list.remove(list.size() - 1); 
        dfs(temp+1, len, ans, list, nums);// 当前这个元素不取,我们直接跳过和它相同的所有元素,即所有元素都不取
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值