leetcode之subset II

来源:互联网 发布:詹姆斯深蹲力量数据 编辑:程序博客网 时间:2024/05/01 06:44

题目

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

     publicArrayList<ArrayList<Integer>> subsetsWithDup(int[] num) {

              ArrayList<ArrayList<Integer>>res = new ArrayList<>();

              if(num == null || num.length == 0) {

                     returnres;

              }

              Arrays.sort(num);

              ArrayList<Integer>list = new ArrayList<>();

              solve(num,0, res, list);

              returnres;

       }

     privatevoid solve(int[] num, int start, ArrayList<ArrayList<Integer>> res,ArrayList<Integer> list) {

              res.add(newArrayList<>(list));

              if(start >= num.length)

                     return;

              for(int i = start; i < num.length; i++) {

                     if(i > start && num[i] == num[i - 1]) {

                            continue;

                     }

                     list.add(num[i]);

                     solve(num,i + 1, res, list);

                     list.remove(list.size()- 1);

              }

       }