Skip to content

Commit f2994cf

Browse files
function for the knapsack problem which returns one of the optimal subsets
1 parent 5d81c55 commit f2994cf

File tree

1 file changed

+22
-1
lines changed

1 file changed

+22
-1
lines changed

dynamic_programming/knapsack.py

Lines changed: 22 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -85,11 +85,32 @@ def knapsack_with_example_solution(W, wt, val):
8585

8686

8787
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
88110
if i > 0 and j > 0:
89111
if dp[i - 1][j] == dp[i][j]:
90112
_construct_solution(dp, wt, i - 1, j, optimal_set)
91113
else:
92-
# item i is certainly part of the solution
93114
optimal_set.add(i)
94115
_construct_solution(dp, wt, i - 1, j - wt[i-1], optimal_set)
95116

0 commit comments

Comments
 (0)