Subsets

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],
  []
]
There is a simpler version, where no duplicates are allowed.


10/31

Algorithm:

take S1 = [1,1,2,2,2,3] for example

start from the list { [ ]  }, in order to be more clear, use { } for the outer layer of list

keep a variable as care which remembers from where the last time elements are added in.

start from { [ ] }

  • consider 1:

{ [ ] , [1] } , care = 1

  • consider 1:

only add from care = 1 to the end

{ [ ] , [1], [1,1]}, care = 2

  • consider 2

because this is the first time that 2 showed up in the list, simply scan from the head of the list to the end, and add 2 to each of the sublist

{ [ ], [1], [1,1],           [2], [1,2], [1,1,2] }, care = 3

  • consider 2 again

this time 2 has shown before, so just scan from care to the end, adding 2 to each sublist

{[ ], [1], [1,1],          [2], [1,2], [1,1,2] ,     [2,2], [1,2,2], [1,1,2 ,2]  }, now care = 6

  • consider 3

this is the first time that 3 shows up, so append 3 to each of the sublist and add to the list

public class Solution {
    public List<List<Integer>> subsetsWithDup(int[] S) {
        Arrays.sort(S); //err1: remember to sort
        int len = S.length;
        List<List<Integer>> list = new ArrayList<List<Integer>>();
        list.add(new ArrayList<Integer>());
        
        int care = 0;
        
        for(int i = 0; i<len; i++){
            int size = list.size();
            if(i > 0 && S[i] == S[i-1]){
                for(int j=care; j<size; j++){
                    List<Integer> newly = new ArrayList<Integer>(list.get(j));
                    newly.add(S[i]);
                    list.add(newly);                    
                }
            }else{
                for(int j=0; j<size; j++){
                    List<Integer> newly = new ArrayList<Integer>(list.get(j));
                    newly.add(S[i]);
                    list.add(newly);
                }
            }
            care = size;
                
        }
        
        
        return list;
    }
}


time complexity and space complexity: not polynomial

considering all distinct elements and checking the i-th element, the length of the list is not polynomial, and you have to copy all the list


Note that this problem itself cannot be polynomial.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值