The problem on LeetCode is as follows:
Given an array of integers nums
and a positive integer k
, return true
if it is possible to divide this array into k
non-empty subsets whose sums are all equal.
nums
can be between 1 and 16.k
?
false
.k
is always a valid integer between 1 and the length of the array?
k
is always valid.k
, return false
.total_sum // k
.def canPartitionKSubsets(nums, k):
total_sum = sum(nums)
# If the total sum is not divisible by k, return False
if total_sum % k != 0:
return False
target_sum = total_sum // k
nums.sort(reverse=True)
# Optimization: if the largest number is greater than the target subset sum, we can't partition
if nums[0] > target_sum:
return False
# Memoization and backtracking setup
used = [False] * len(nums)
def backtrack(start, k, current_sum):
# Base case: if only one subset left, it will have the correct sum
if k == 0:
return True
# Base case: if current subset's sum is achieved, start new subset
if current_sum == target_sum:
return backtrack(0, k - 1, 0)
# Try to fill the current subset
for i in range(start, len(nums)):
if not used[i] and current_sum + nums[i] <= target_sum:
used[i] = True
if backtrack(i + 1, k, current_sum + nums[i]):
return True
used[i] = False # backtrack
return False
return backtrack(0, k, 0)
O(n log n)
where n
is the length of the array.O(2^n)
, since each element can either be in a subset or not.Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?