Here: full solution for partitioning into K equal subsets:
plaintext function canPartitionKSubsets(nums, k) total := sum of nums if total % k . = 0 then return false target := total / k n := length of nums dp := array of size 2^n, filled with -1 dp[0] := 0 for mask := 0 to 2^n - 1 if dp[mask] = -1 then continue for i := 0 to n - 1 if (mask >> i) & 1 = 1 then continue if dp[mask] + nums[i] > target then continue newMask := mask | (1 << i) dp[newMask] := (dp[mask] + nums[i]) % target return dp[2^n - 1] = 0
When the sum hits target, the modulo operation resets it to , starting a fresh subset.
Time: . Space: .
Time: . Space: .