- Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path90-Subsets-II.py
39 lines (27 loc) · 845 Bytes
/
90-Subsets-II.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
'''Leetcode- https://leetcode.com/problems/subsets-ii/'''
'''
Given an integer array nums that may contain duplicates, return all possible subsets (the power set).
The solution set must not contain duplicate subsets. Return the solution in any order.
Example 1:
Input: nums = [1,2,2]
Output: [[],[1],[1,2],[1,2,2],[2],[2,2]]
'''
defsubsetsWithDup(nums):
res= []
nums.sort()
defbacktrack(i, subset):
ifi==len(nums):
res.append(subset[::])
return
# All subsets that include nums[i]
subset.append(nums[i])
backtrack(i+1, subset)
subset.pop()
# All subsets that don't include nums[i]
whilei+1<len(nums) andnums[i] ==nums[i+1]:
i+=1
backtrack(i+1, subset)
backtrack(0, [])
returnres
#T:O(n.2^n)
#S:O(n)