Skip to content

Instantly share code, notes, and snippets.

@goish135
Created July 20, 2021 08:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save goish135/71f2ebc650e03d9ee4141279b106b9c4 to your computer and use it in GitHub Desktop.
Save goish135/71f2ebc650e03d9ee4141279b106b9c4 to your computer and use it in GitHub Desktop.
weight = [4,5,6,2,2]
value = [6,4,5,3,6]
W = 8 # 負重
num = len(value)
# or num = len(weight)
# ans = 15 # 最大價值
# 0 1 2 3 4 5 6 7 8
# 0 0 0 0 0 0 0 0 0 0
# 1 0
# 2 0
# 3 0
# 4 0
# 5 0
#print([ [0] * (W+1) for _ in range(len(value)+1) ] )
dp = [ [0] * (W+1) for _ in range(len(value)+1) ]
for i in range(1,num+1): # row 第幾個物品
for j in range(1,W+1):
# 要加物品 大於 現在負重
if weight[i-1] > j :
dp[i][j] = dp[i-1][j]
# 要加物品 沒有大於 現在負重
else:
dp[i][j] = max(dp[i-1][j],dp[i-1][j-weight[i-1]]+value[i-1])
print(dp[num][W])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment