Leetcode : Subsets II

URL:

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

题目大意:

Given a collection of integers that might contain duplicates, nums, return all possible subsets.

Note: The solution set must not contain duplicate subsets.

For example,
If nums = [1,2,2], a solution is:

[
[2],
[1],
[1,2,2],
[2,2],
[1,2],
[]
]

解题思路:

本题基本的深度优先搜索就可以解决问题。但是需要注意2点:

 1. 数组中存在相同的数值,所以在进行深度优先搜索之前先进行排序,这样就可以在遍历的时候过滤掉相同的数值。
 2. 在一次递归结束之前要把本次递归新加入的元素删除掉

下面给出代码

代码示例

public class Solution {
    private List<List<Integer>> result = new ArrayList<>();//用一个全局变量保存最后的结果

//深度优先搜索的方法
    void dfs(int[]nums,int index,List<Integer>row){
        row.add(nums[index]);//将当前位置的数值添加到List
        this.result.add(new ArrayList<>(row));//当前List添加到最终结果中
        //从当前位置之后进行遍历,对于不重复的数值进行递归
        for(int i=index+1;i<nums.length;i++){

            if(i==index+1||nums[i]!=nums[i-1]){
                dfs(nums,i,row);
            }
        }
        //递归结束前删除我们本次添加的数据
        row.remove(row.size()-1);
    }

    public List<List<Integer>> subsetsWithDup(int[] nums) {
    //先进行排序
        Arrays.sort(nums);
        //把我们的全局变量清空一下
        result.clear();
        //把空集合先添加进来
        result.add(new ArrayList<>());
        for(int i=0;i<nums.length;i++){
            if(i==0||nums[i]!=nums[i-1]){
                dfs(nums,i,new ArrayList<>());
            }
        }
        //返回最终结果
        return result;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值