[Leetcode] Subsets II

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:

 1 public class Solution {
 2     public List<List<Integer>> subsetsWithDup(int[] num) {
 3         Arrays.sort(num);
 4         List<List<Integer>> result = new ArrayList<List<Integer>>();
 5         List<Integer> al = new ArrayList<Integer>();
 6         dfs(result, al, num, 0);
 7         return result;
 8     }
 9 
10     private void dfs(List<List<Integer>> result, List<Integer> al, int[] s,
11             int start) {
12         // TODO Auto-generated method stub
13         result.add(new ArrayList<Integer>(al));
14         for (int i = start; i < s.length; ++i) {
15             al.add(s[i]);
16             dfs(result, al, s, i+1);
17             al.remove(al.size()-1);
18             while((i+1<s.length)&&(s[i]==s[i+1]))
19                 ++i;
20         }
21     }
22 }
原文地址:https://www.cnblogs.com/Phoebe815/p/4094064.html