Skip to content

Instantly share code, notes, and snippets.

@goish135
Last active July 20, 2021 11:42
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/42e360ee5f40e8b1e971ae764acb5fa9 to your computer and use it in GitHub Desktop.
Save goish135/42e360ee5f40e8b1e971ae764acb5fa9 to your computer and use it in GitHub Desktop.
# 0-1 Knapsack Problem 0-1 背包問題
'''
[0, 0, 0, 0, 0, 0, 0, 0, 0]
[0, 0, 0, 0, 6, 6, 6, 6, 6]
[0, 0, 0, 0, 6, 6, 6, 6, 6]
[0, 0, 0, 0, 6, 6, 6, 6, 6]
[0, 0, 3, 3, 6, 6, 9, 9, 9]
[0, 0, 6, 6, 9, 9, 12, 12, 15]
ans: [0, 0, 6, 6, 9, 9, 12, 12, 15]
'''
weight = [4,5,6,2,2]
value = [6,4,5,3,6]
W = 8 # 負重
num = len(value)
# NUM = len(value)
# ans = 15 # 最大價值
# dp[目前重量] = 價值
## dp[限重] = 最大價值
dp = [0] * (W+1)
print(dp)
dp =[0] * (W+1)
for i in range(1,num+1): # row 第幾個物品
for j in range(W,weight[i-1]-1,-1):
dp[j] = max(dp[j-weight[i-1]]+value[i-1],dp[j]) # 根據 現在負重 vs (現在負重-加入物品重)
print(dp)
print("ans:",dp)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment