Leetcode no. 90

来源:互联网 发布:财务软件 知乎 编辑:程序博客网 时间:2024/04/28 20:52

90. Subsets II

 

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

Note:

  • Elements in a subset must be in non-descending order.
  • 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],  []]
public class Solution {    public List<List<Integer>> subsetsWithDup(int[] nums) {        List<List<Integer>> list= new LinkedList<>();        list.add(new LinkedList<>());        if (nums.length==0) return list;        Arrays.sort(nums);        int prev= nums[0], count=1;        List<List<Integer>> previous= new LinkedList<>(list);        for (int i = 0; i < nums.length; i++) {            List<List<Integer>> sublist= new LinkedList<>();            if (i>0 && nums[i] == prev) {                count++;                for (List<Integer> ele: previous) {                    List<Integer> tmp = new LinkedList<>(ele);                    for (int j = 0; j < count; j++) {                        tmp.add(nums[i]);                    }                    sublist.add(tmp);                }            } else {                for (List<Integer> ele : list) {                    List<Integer> tmp = new LinkedList<>(ele);                    tmp.add(nums[i]);                    sublist.add(tmp);                    count = 1;                    prev= nums[i];                    previous= new LinkedList<>(list);                }            }            list.addAll(sublist);        }        return list;    }}



 

0 0
原创粉丝点击