-
Notifications
You must be signed in to change notification settings - Fork 0
/
knapsack.py
51 lines (28 loc) · 840 Bytes
/
knapsack.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
def recurKnapsack(profit, weight, capacity, i):
if i == len(profit):
return 0
if capacity<0:
return 0
mx = 0
if capacity>=weight[i]:
mx = max(recurKnapsack(profit,weight,capacity-weight[i],i+1)+profit[i],recurKnapsack(profit,weight,capacity,i+1))
print(capacity)
print(mx)
return mx
profit = [1,6,10,16]
weight = [1,2,3,5]
capacity = 7
dp = [[0 for i in range(capacity+1)] for j in range(len(profit))]
def dpKnapsack(profit, weight, capacity, i):
if i == len(profit):
return 0
if capacity<0:
return 0
if dp[i][capacity] > 0:
return dp[i][capacity]
if capacity>=weight[i]:
dp[i][capacity] = max(dpKnapsack(profit,weight,capacity-weight[i],i+1)+profit[i],dpKnapsack(profit,weight,capacity,i+1))
# print(capacity)
# print(mx)
return dp[i][capacity]
print(dpKnapsack(profit,weight,capacity,0))