Recursively reconstructs one of the optimal subsets given a filled DP table and the vector of weights Parameters ---------- * `dp`: list of list, the table of a solved integer weight dynamic programming problem * `wt`: list or tuple, the vector of weights of the item
(dp: list, wt: list, i: int, j: int, optimal_set: set)
| 101 | |
| 102 | |
| 103 | def _construct_solution(dp: list, wt: list, i: int, j: int, optimal_set: set): |
| 104 | """ |
| 105 | Recursively reconstructs one of the optimal subsets given |
| 106 | a filled DP table and the vector of weights |
| 107 | |
| 108 | Parameters |
| 109 | ---------- |
| 110 | |
| 111 | * `dp`: list of list, the table of a solved integer weight dynamic programming |
| 112 | problem |
| 113 | * `wt`: list or tuple, the vector of weights of the items |
| 114 | * `i`: int, the index of the item under consideration |
| 115 | * `j`: int, the current possible maximum weight |
| 116 | * `optimal_set`: set, the optimal subset so far. This gets modified by the function. |
| 117 | |
| 118 | Returns |
| 119 | ------- |
| 120 | |
| 121 | ``None`` |
| 122 | """ |
| 123 | # for the current item i at a maximum weight j to be part of an optimal subset, |
| 124 | # the optimal value at (i, j) must be greater than the optimal value at (i-1, j). |
| 125 | # where i - 1 means considering only the previous items at the given maximum weight |
| 126 | if i > 0 and j > 0: |
| 127 | if dp[i - 1][j] == dp[i][j]: |
| 128 | _construct_solution(dp, wt, i - 1, j, optimal_set) |
| 129 | else: |
| 130 | optimal_set.add(i) |
| 131 | _construct_solution(dp, wt, i - 1, j - wt[i - 1], optimal_set) |
| 132 | |
| 133 | |
| 134 | if __name__ == "__main__": |
no test coverage detected