LeetCode刷题【Array】 Subsets II

来源:互联网 发布:淘宝零食销量排行 编辑:程序博客网 时间:2024/06/15 14:42

题目:

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

解决方法一: 回溯法:Runtime: 3 ms

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

参考:

【1】https://leetcode.com/


0 0
原创粉丝点击