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

解题思路: 跟subset 基本一样,就是多加一条判断重复,如果有重复, i++;

public class Solution {
    public ArrayList<ArrayList<Integer>> subsetsWithDup(int[] num) {
        Arrays.sort(num);
        ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();
        ArrayList<Integer> output = new ArrayList<Integer>();
        generate(0, num.length, num, output, result);
        return result;
    }
    
    public void generate(int depth, int len, int[] num, ArrayList<Integer> output, ArrayList<ArrayList<Integer>> result){
        result.add(output);
        
        if(depth == len)
            return;
            
        for(int i = depth; i < len; i++){
            ArrayList<Integer> tmp = new ArrayList<Integer>();
            tmp.addAll(output);
            tmp.add(num[i]);
            generate(i+1, num.length, num, tmp, result);
            
            while(i+1 < len && num[i] == num[i+1] ){
                i++;
            }
            
        }
    }
}

 

posted @ 2014-02-13 14:04  Razer.Lu  阅读(127)  评论(0编辑  收藏  举报