程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Python 0/1 knapsack problem

編輯:Python
def knapsack(i, capacity):
if n == 1:
dp[i] = 1
return
if v_all[i][capacity] == -1:
if i == 0 or capacity == 0:
v_all[i][capacity] = 0
elif s[i] > capacity:
v_all[i][capacity] = 0
knapsack(i - 1, capacity)
else:
s1 = knapsack(i - 1, capacity - s[i]) + v[i]
s2 = knapsack(i - 1, capacity)
if s1 >= s2:
dp[i] = 1
v_all[i][capacity] = s1
else:
dp[i] = 0
v_all[i][capacity] = s2
return v_all[i][capacity]
n = 5
v = [100, 200, 300, 150, 120]
s = [300, 200, 150, 200, 100]
capacity = 500
dp = [0] * n
v_all = []
for i in range(n):
temp = [-1] * (capacity + 1)
v_all.append(temp)
knapsack(n - 1, capacity)
print(dp)


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved