Backpack IV

Backpack IV (LI.562)

Given n items, an integer array sizes and a target, find the number of possible subsets of items to fill the backpack.

Example

I: sizes=[2,3,6,7], target=7
O: [ [2,2,3], [7] ] = 2

Notice: [2,3,2] and [3,2,2] are not taken into account

Analysis

Because we want subsets instead of combinations, this is a 0/1 knapsack problem.

Approach 1

1. Optimal subproblem
    kp[s] = maximum number of ways to fill size s
2. Recurrence
    if s < size[i]: kp[s] += 0 do nothing
    else if size[i] <= s: kp[s] += kp[s-size[i]]
3. Topo Order (0/1 is different from full)
    for i from 0 to n-1
        for s from 1 to target
4. Base case
    kp[0] = 1
    b/c there's only one way to fill an empty bag (no items [] subset)
5. Final answer
    kp[target]

State Graph 1

Code 1

Approach 2

State Graph 2

Code 2

The recurrence below is wrong. It failed to enumerate all the occurrences of item i. Why does it differ from approach 1?

Last updated