File tree Expand file tree Collapse file tree 1 file changed +25
-0
lines changed
Expand file tree Collapse file tree 1 file changed +25
-0
lines changed Original file line number Diff line number Diff line change @@ -736,7 +736,32 @@ class Solution:
736736```
737737
738738``` Python
739+ def backPack (weight , value , bagweight ):
740+ # 二维数组
741+ dp = [[0 ] * (bagweight + 1 ) for _ in range (len (weight))]
742+
743+ # 初始化
744+ for j in range (weight[0 ], bagweight + 1 ):
745+ dp[0 ][j] = value[0 ]
746+
747+ # weight数组的大小就是物品个数
748+ for i in range (1 , len (weight)): # 遍历物品
749+ for j in range (bagweight + 1 ): # 遍历背包容量
750+ if j < weight[i]:
751+ dp[i][j] = dp[i - 1 ][j]
752+ else :
753+ dp[i][j] = max (dp[i - 1 ][j], dp[i - 1 ][j - weight[i]] + value[i])
754+
755+ return dp[len (weight) - 1 ][bagweight]
756+
757+ if __name__ == " __main__" :
758+
759+ weight = [1 , 3 , 4 ]
760+ value = [15 , 20 , 30 ]
761+ bagweight = 4
739762
763+ result = backPack(weight, value, bagweight)
764+ print (result)
740765```
741766
742767### [ backpack-ii] ( https://www.lintcode.com/problem/backpack-ii/description )
You can’t perform that action at this time.
0 commit comments