|
| 1 | +""" |
| 2 | +If we use the solution from the [last question](https://leetcode.com/problems/subsets/), |
| 3 | +We will notice that it will have some duplicates. |
| 4 | +This is because if you have three 2 (`[2, 2, 2]`). |
| 5 | +You might choosing two different sets of 2 and end up looking the same. |
| 6 | +For example, you choose the first and the second => `[2, 2]` |
| 7 | +You choose the second and the third => `[2, 2]` |
| 8 | +
|
| 9 | +One workaround I did is just using hash-set. |
| 10 | +``` |
| 11 | +return list(set([tuple(combination) for combination in answer])) |
| 12 | +``` |
| 13 | +This cause us really high time complexity. |
| 14 | +Since turning list to tuple and tuple to list is actually O(N) in theory. |
| 15 | +
|
| 16 | +Time complexity would be `O((2^N) * N)` be cuase for each element in the answer we need to convert it to tuple and back. |
| 17 | +""" |
| 18 | +class Solution(object): |
| 19 | + def subsetsWithDup(self, nums): |
| 20 | + nums.sort() |
| 21 | + answer = [[]] |
| 22 | + for num in nums: |
| 23 | + new_subs = [] |
| 24 | + for sub in answer: |
| 25 | + new_subs.append(sub+[num]) |
| 26 | + answer.extend(new_subs) |
| 27 | + return list(set([tuple(combination) for combination in answer])) |
| 28 | + |
| 29 | +""" |
| 30 | +I found the best solution and explaination is made by @ZitaoWang's answer and here is his [explaination](https://leetcode.com/problems/subsets-ii/discuss/171626/Python-solution). I copied from it. |
| 31 | +For example, `nums = [1,1,2,2,2,4,4,5]`. In this case, `counter = {1:2, 2:3, 4:2, 5:1}`. |
| 32 | +We intialize `answer = [[]]` and build the solution iteratively as we loop over the counter. |
| 33 | +We first reach `num, count = 1, 2`. The power set of [1,1] is `[[], [1], [1,1]]`. |
| 34 | +Then we reach `num, count = 2, 3`. |
| 35 | +The power set of [1,1,2,2,2] is obtained by appending either zero, one, two or three 2's to all elements in `answer`. |
| 36 | +After which we get answer = [[], [1], [1,1], [2], [1,2], [1,1,2],[2,2], [1,2,2], [1,1,2,2],[2,2,2], [1,2,2,2], [1,1,2,2,2]]. |
| 37 | +After we loop over counter, answer will be the power set of nums. |
| 38 | +
|
| 39 | +Time complexity: `O(2^N)`, space complexity: `O(2^N)`. |
| 40 | +""" |
| 41 | +from collections import Counter |
| 42 | + |
| 43 | +class Solution(object): |
| 44 | + def subsetsWithDup(self, nums): |
| 45 | + counter = Counter(nums) |
| 46 | + answer = [[]] |
| 47 | + |
| 48 | + for num, count in counter.items(): |
| 49 | + power_set = [[num]*c for c in xrange(1, count+1)] |
| 50 | + for i in xrange(len(answer)): |
| 51 | + for s in power_set: |
| 52 | + answer.append(answer[i]+s) |
| 53 | + return answer |
0 commit comments