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 }

 

转载于:https://www.cnblogs.com/feiling/p/3256589.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值