Skip to content

Commit dd1a32f

Browse files
committed
背包问题 II
1 parent 7e439fe commit dd1a32f

File tree

1 file changed

+21
-0
lines changed

1 file changed

+21
-0
lines changed

backpack_ii.py

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
# -*- coding: utf-8 -*-
2+
3+
class Solution:
4+
# @param m: An integer m denotes the size of a backpack
5+
# @param A & V: Given n items with size A[i] and value V[i]
6+
# @return: The maximum value
7+
def backPackII(self, m, A, V):
8+
# write your code here
9+
'''
10+
肯定是动态规划!
11+
dp[i][j]表示前i个商品在j空间能获得的最大价值。
12+
1. 如果不放第i个商品:d[i][j] = dp[i - 1][j]
13+
2. 如果放第i个商品:d[i][j] = dp[i - 1][j] + v[i]
14+
注意:A是体积,V是价值。
15+
'''
16+
ret = [0] * (m + 1)
17+
for i in xrange(len(A)):
18+
for j in xrange(m, -1, -1):
19+
if j >= A[i]: # 有足够的体积容纳第i件商品
20+
ret[j] = max(ret[j], ret[j - A[i]] + V[i])
21+
return ret[-1]

0 commit comments

Comments
 (0)