Backpack II

Question

Problem Statement

Given n items with size $$Ai$$ and value Vi, and a backpack with size m. What's the maximum value can you put into the backpack?

Example

Given 4 items with size [2, 3, 5, 7] and value [1, 5, 2, 4], and a backpack with size 10. The maximum value is 9.

Note

You cannot divide item into small pieces and the total size of items you choose should smaller or equal to m.

Challenge

O(n x m) memory is acceptable, can you do it in O(m) memory?

题解

首先定义状态 $$K(i,w)$$ 为前 $$i$$ 个物品放入size为 $$w$$ 的背包中所获得的最大价值,则相应的状态转移方程为:

$$K(i,w) = \max {K(i-1, w), K(i-1, w - w_i) + v_i}$$ 详细分析过程见 Knapsack

class Solution:
    # @param m: An integer m denotes the size of a backpack
    # @param A & V: Given n items with size A[i] and value V[i]
    def backPackII(self, m, A, V):
        # write your code here
        f = [0 for i in xrange(m+1)]
        n = len(A)
        for i in range(n):
            for j in xrange(m, A[i]-1, -1):
                f[j] = max(f[j] , f[j-A[i]] + V[i])
        return f[m]

sol=Solution()
A=[2, 3, 5, 7]
V=[1, 5, 2, 4]
m=10
sol.backPackII(m,A,V)

results matching ""

    No results matching ""