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唯一区别在于输入会有重复元素,这是面试时需要注意的,尽可能考虑所有输入情况
代码与上一题只在25-27有区别,当发现重复元素时则跳过


 1 public class Solution {
 2     public ArrayList<ArrayList<Integer>> subsetsWithDup(int[] num) {
 3         // Start typing your Java solution below
 4         // DO NOT write main() function
 5         Arrays.sort(num);
 6         ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();
 7         ArrayList<Integer> output = new ArrayList<Integer>();
 8         generate(result, output, 0, num, num.length);
 9         return result;
10     }
11     
12      public void generate(ArrayList<ArrayList<Integer>> result, ArrayList<Integer> output,
13                     int depth, int[] S, int len){
14         result.add(output);
15         if(depth == len){
16             return;
17         }
18         
19         for(int i = depth; i < len; i++){
20             ArrayList<Integer> tmp = new ArrayList<Integer>();
21             tmp.addAll(output);
22             tmp.add(S[i]);
23             generate(result, tmp, i + 1, S, len);
24             
25             while(i + 1 < len && S[i] == S[i+1]){
26                 i++;
27             }
28         }
29     }
30 }

 

posted @ 2013-08-14 10:16  feiling  阅读(246)  评论(0编辑  收藏  举报