awelgorithms

Reconstruct the chosen knapsack items

Updated

Store a take-bit take[i][w] (or parent) when the rec prefers take. After filling, walk i=n, w=W: if take[i][w], emit item i-1 and set w-=a[i-1], else i-=1. Do not re-solve from values alone when ties exist — follow the bits you wrote.

What to focus on

Reconstruction needs the decision table, not only dp[n][W]. Walking greedy-largest from the original array can disagree with the DP choice.

Worked examples

W=5 items 1 and 4

a = [1, 4, 9], W = 5
  1. take[2][5] skip 9, w stays 5
  2. take 4, w=1
  3. take 1, w=0

Result: [1, 4]

W=10 items 1 and 9

a = [1, 4, 9], W = 10
  1. take 9, w=1
  2. skip 4
  3. take 1

Result: [1, 9]

W=9 item 9

a = [1, 4, 9], W = 9
  1. take 9, w=0
  2. stop

Result: [9]

Try it

Write reconstruct(a, W). a is item weights. W is capacity. value equals weight. take[i][w] is true if item i-1 was taken at capacity w. Backtrack take[]. Print the item list in the order you emit them. W=5 → [1, 4]. W=10 → [1, 9]. W=9 → [9].

Capacity W and item weights are positive. n = 3. value equals weight. A solution exists; reconstruct it.