Problem
Given an integer array nums
and an integer k
, return true
if it is possible to divide this array into k
non-empty subsets whose sums are all equal.
Examples
Example 1:
|
|
Example 2:
|
|
Similar problems
Solution
Method 1 - Backtracking
We can use visited
boolean array to track if the value is part of some subset. Then we go deeper into DFS. For each partition, targetSum
is sum(nums)/k
.
Base Case
- if we reach
k = 1
, then we have reached target - if
currSum > targetSum
then we returnfalse
Actual Recursion
- If we
currSum
istargetSum
, and there arek's
more than 1, then we find thetargetSum
again withk - 1
partition. - If not, go through array and see if we can find
k
partitions and backtrack if we couldn’t find answer in that path
Code
|
|
Complexity
- ⏰ Time complexity:
O(k*2^n)
because we runk
iterations for recursion, and in that we have2^n
choices to create the subset such that sum is equal tosum(nums)/k
. - 🧺 Space complexity:
O(n)
forvisited
set, recursion stack, etc