LeetCode in Java [11]: 90. Subsets II

允我心安 提交于 2020-01-25 01:38:30

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

Backtrack就完事了,记得先排序一下,结果:

Success

Runtime: 1 ms, faster than 99.06% of Java online submissions for Subsets II.

Memory Usage: 37.5 MB, less than 98.53% of Java online submissions forSubsets II.

class Solution {
    private List<List<Integer>> res;
    public List<List<Integer>> subsetsWithDup(int[] nums) {
        res=new ArrayList<>();
        ArrayList<Integer> temp=new ArrayList<>();
        res.add(new ArrayList<>(temp));
        if(nums==null||nums.length==0){return res;}
        Arrays.sort(nums);
        findsubs(nums,temp,0);
        return res;
    }
    private void findsubs(int[] nums,List<Integer> cur,int bound){
        for(int i=bound;i<nums.length;i++){
            cur.add(nums[i]);
            res.add(new ArrayList<>(cur));
            findsubs(nums,cur,i+1);
            cur.remove(cur.size()-1);
            while((i+1)<nums.length&&nums[i+1]==nums[i]){i++;}
        }
    }
}

 

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!