@@ -85,11 +85,32 @@ def knapsack_with_example_solution(W, wt, val):
85
85
86
86
87
87
def _construct_solution (dp , wt , i , j , optimal_set ):
88
+ """
89
+ Recursively reconstructs one of the optimal subsets given
90
+ a filled DP table and the vector of weights
91
+
92
+ Parameters
93
+ ---------
94
+
95
+ dp: list of list, the table of a solved integer weight dynamic programming problem
96
+
97
+ wt: list or tuple, the vector of weights of the items
98
+ i: int, the index of the item under consideration
99
+ j: int, the current possible maximum weight
100
+ optimal_set: set, the optimal subset so far. This gets modified by the function.
101
+
102
+ Returns
103
+ -------
104
+ None
105
+
106
+ """
107
+ # for the current item i at a maximum weight j to be part of an optimal subset,
108
+ # the optimal value at (i, j) must be greater than the optimal value at (i-1, j).
109
+ # where i - 1 means considering only the previous items at the given maximum weight
88
110
if i > 0 and j > 0 :
89
111
if dp [i - 1 ][j ] == dp [i ][j ]:
90
112
_construct_solution (dp , wt , i - 1 , j , optimal_set )
91
113
else :
92
- # item i is certainly part of the solution
93
114
optimal_set .add (i )
94
115
_construct_solution (dp , wt , i - 1 , j - wt [i - 1 ], optimal_set )
95
116
0 commit comments