2025-09-16 10:01
Status: adult
Tags: leetcode leetcode-medium backtrack Leetcode Backtracking Intro Subsets
Subsets II
Code
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:
- Space complexity:
- extra space.
- 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 = while being sure that i doesn’t go out of bounds.
- call backtrack