Backpack III 完全背包

Given n kind of items with size Ai and value Vi( each item has an infinite number available) and a backpack with size m. What's the maximum value can you put into the backpack?

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 15.

完全背包问题,即每件物体可取任意件。dp[i,j]表示为前i个物体填满背包可获得的最大价值。DP方程转换为dp[i,j] = max(dp[i-1,j], dp[i, j - Ai] + Vi)。这样转换的复杂度为O(NV),要快于从0-1背包转化过来的从i-1上讨论的转化方程O(NV^2)。

注意这里与0-1背包不一样因为第i件物品可以添加多件.所以DP可以在已加入当前物体的状态下继续添加.

代码入下:

class Solution:
    # @param {int[]} A an integer array
    # @param {int[]} V an integer array
    # @param {int} m an integer
    # @return {int} an array
    def backPackIII(self, A, V, m):
        n = len(A)
        dp = [0] * (m + 1)
        for i in xrange(n):
            for j in xrange(A[i], m + 1):
                dp[j] = max(dp[j], dp[j - A[i]] + V[i])
        
        return dp[m]

 

posted on 2016-07-18 15:56  Sheryl Wang  阅读(286)  评论(0编辑  收藏  举报

导航