Leetcode : Subsets II

来源:互联网 发布:光环大数据怎么样 编辑:程序博客网 时间:2024/05/20 08:22

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;    }}
原创粉丝点击