Dynamic Programming21 sections · 916 units
Open in Course

K Subsets - Implementation

The code

Here: full solution for partitioning into K equal subsets:

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 00, starting a fresh subset.

Time: O(n2n)O(n \cdot 2^n). Space: O(2n)O(2^n).

Time: O(n2n)O(n \cdot 2^n). Space: O(2n)O(2^n).