This problem has two parts. The first part is a proof: a dynamic programming table stores the optimum value of every subproblem, and the reconstruction procedure repeatedly walks to a predecessor whose transition attained that table entry. Prove that this backtracking returns an optimal sequence of decisions, not merely a feasible one. Both approaches below carry that theorem in full, including the induction, the termination argument, the tie analysis, and the exchange argument.
The second part is an executable companion that instantiates the theorem instead of restating it. The companion is 0/1 knapsack reconstruction, so the returned value is a concrete witness and not a claim.
You are given items, where items[i] = [weight_i, value_i], and the integer capacity. Each item may be selected at most once. Define the value table over prefixes and capacities:
dp[0][c] = 0 for every capacity.
- For
i >= 1 and weight_i <= c, dp[i][c] = max(dp[i-1][c], dp[i-1][c - weight_i] + value_i).
- For
i >= 1 and weight_i > c, dp[i][c] = dp[i-1][c].
Return the indices of the items selected by the reconstruction that starts at state (n, capacity), where n = items.length, and moves to a base state:
- If
dp[i][c] == dp[i-1][c], the same optimum value is reachable without item i, so skip item i and continue from (i-1, c).
- Otherwise item
i belongs to every optimal solution of state (i, c), so record index i-1 and continue from (i-1, c - weight_i).
The equality test is also the tie rule: whenever excluding the current item preserves the optimum, the item is excluded. That makes the witness unique and the expected answer a single index list. The witness is guaranteed to be a maximum value subset, and that guarantee is the theorem proved below: the table value of the remaining state is carried exactly by the reconstructed prefix.
Return the recorded indices in increasing order. Empty input, overweight items, zero value items, and zero weight items are all legal.