[LeetCode]Subsets II

来源:互联网 发布:刘飞儿faye知乎 编辑:程序博客网 时间:2024/05/17 07:25

Question
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],  []]

本题难度Medium。

【复杂度】
时间 O(N) 空间 O(N)

【思路】
与[LeetCode]Subsets差不多,区别有两点:

  1. 有重复的数字
  2. 因为有重复,所以需要先进行排序

只要在循环中加入判断:if(i==index||nums[i-1]!=nums[i]) (19行)即可。

【代码】

public class Solution {    public List<List<Integer>> subsetsWithDup(int[] nums) {        //require        List<List<Integer>> ans=new LinkedList<>();        ans.add(new LinkedList<Integer>());        Arrays.sort(nums);        //invariant        helper(0,new LinkedList<Integer>(),nums,ans);        //ensure        return ans;    }    private void helper(int index,List<Integer> preList,int[] nums,List<List<Integer>> ans){        int size=nums.length;        //base case        if(index==size)            return;        for(int i=index;i<size;i++){            if(i==index||nums[i-1]!=nums[i]){                preList.add(nums[i]);                ans.add(new LinkedList<Integer>(preList));                helper(i+1,preList,nums,ans);                preList.remove(preList.size()-1);            }        }    }}
0 0
原创粉丝点击