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:
|
|
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 > targetSumthen we returnfalse
Actual Recursion
- If we
currSumistargetSum, and there arek'smore than 1, then we find thetargetSumagain withk - 1partition. - If not, go through array and see if we can find
kpartitions and backtrack if we couldn’t find answer in that path
Code
|
|
Complexity
- ⏰ Time complexity:
O(k*2^n)because we runkiterations for recursion, and in that we have2^nchoices to create the subset such that sum is equal tosum(nums)/k. - 🧺 Space complexity:
O(n)forvisitedset, recursion stack, etc