首页 > 代码库 > Leetcode: Subsets II

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

与Subsets问题的唯一区别在于,一个满足条件的set加入到最终结果sets里面的时候,需要先检查sets里面是否已经存在这个set,如果重复,则不添加。

这还是一道列举所有case的NP的题,用recursion, 用arraylist

 1 import java.util.*; 2  3 public class Solution { 4     public ArrayList<ArrayList<Integer>> subsetsWithDup(int[] num) { 5         java.util.Arrays.sort(num); 6         ArrayList<Integer> set = new ArrayList<Integer>(); 7         ArrayList<ArrayList<Integer>> sets = new ArrayList<ArrayList<Integer>>(); 8          9         for (int i = 0; i <= num.length; i++) {10             helper(set, sets, num, i, 0);11         }12         return sets;13     }14     15     public void helper(ArrayList<Integer> set, ArrayList<ArrayList<Integer>> sets, int[] num, int i, int start) {16         if (set.size() == i) {17             if (!sets.contains(set)) {18                 sets.add(new ArrayList<Integer>(set));19             }20             return;21         }22         for (int k = start; k < num.length; k++) {23             set.add(num[k]);24             helper(set, sets, num, i, k+1);25             set.remove(set.size() - 1);26         }27     }28 }

 

Leetcode: Subsets II