Subsets II

来源:互联网 发布:淘宝旺铺多少钱一个月 编辑:程序博客网 时间:2024/06/05 00:49

Q:

Given a collection of integers that might contain duplicates, S, 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 S = [1,2,2], a solution is:

[  [2],  [1],  [1,2,2],  [2,2],  [1,2],  []]

Solution:

public class Solution {    public List<List<Integer>> subsetsWithDup(int[] num) {        List<List<Integer>> result = new ArrayList<List<Integer>>();        List<Integer> list = new ArrayList<Integer>();        result.add(list);        Arrays.sort(num);        generate(result, num, 0, list);        return result;    }    void generate(List<List<Integer>> result, int[] num, int start, List<Integer> list) {        for (int i = start; i < num.length; i++) {            list.add(num[i]);            result.add(new ArrayList<Integer>(list));            generate(result, num, i+1, list);            list.remove(list.size()-1);            while (i < num.length - 1 && num[i] == num[i+1])                i++;        }    }}


0 0
原创粉丝点击