class Solution(object): def subsetsWithDup(self, nums): """ :type nums: List[int] :rtype: List[List[int]] """ # backtracking problem res, sol = [], [] nums.sort() n = len(nums) def backtrack(i): # base case if i == n: res.append(sol[:]) return # include nums[i] sol.append(nums[i]) backtrack(i + 1) sol.pop() # not include nums[i] while i + 1 < n and nums[i] == nums[i + 1]: i += 1 backtrack(i + 1) backtrack(0
Time complexity: O(n∗2n)
Space complexity:
O(n) extra space.
O(2n) space for the output list.
Explanation
Very similar to Subsets but since there are duplicates, we have to sort nums first
Base case: if the index = length of nums
Choices:
Include nums[i]: append, backtrack, pop
Not include nums[i]: 2 conditions we have to check:
since there are duplicates, we need to avoid them by checking that nums[i] = nums[i+1] while being sure that i doesn’t go out of bounds.