forked from wangzheng0822/algo
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request wangzheng0822#214 from jerryderry/dp-python
0/1 knapsack problem in python
- Loading branch information
Showing
1 changed file
with
30 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,30 @@ | ||
""" | ||
Author: Wenru Dong | ||
""" | ||
|
||
from typing import List | ||
|
||
def knapsack01(weights: List[int], values: List[int], capacity: int) -> int: | ||
# Denote the state as (i, c), where i is the stage number, | ||
# and c is the capacity available. Denote f(i, c) to be the | ||
# maximum value when the capacity available is c, and Item 0 | ||
# to Item i-1 are to be packed. | ||
# The goal is to find f(n-1, W), where W is the total capacity. | ||
# Then the DP functional equation is: | ||
# f(i, c) = max(xᵢvᵢ + f(i-1, c-xᵢwᵢ)), xᵢ ∈ D, i ≥ 0, | ||
# f(-1, c) = 0, 0 ≤ c ≤ W, | ||
# where | ||
# / {0}, if wᵢ > c | ||
# D = D(i, c) = | ||
# \ {0, 1}, if wᵢ ≤ c | ||
|
||
prev = [0] * (capacity + 1) | ||
for w, v in zip(weights, values): | ||
prev = [c >= w and max(prev[c], prev[c-w] + v) for c in range(capacity + 1)] | ||
return prev[-1] | ||
|
||
|
||
if __name__ == "__main__": | ||
# To find the maximum weight that can be packed, | ||
# set values equal to the weights | ||
print(knapsack01([2, 2, 4, 6, 3], [2, 2, 4, 6, 3], 9)) |