python 125. Backpack II

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?

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

Have you met this question in a real interview?   Yes

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.



使用动态规划:


解法一:


class Solution:
    """
    @param m: An integer m denotes the size of a backpack
    @param A: Given n items with size A[i]
    @param V: Given n items with value V[i]
    @return: The maximum value
    """

    def backPackII(self, m, A, V):
        # write your code here
        M = len(A) + 1
        N = m + 1
        dp = [[0 for i in range(N) ] for j in range(M)]

        for i in range(1, M ):
            for j in range(N):
                if j < A[i - 1]:
                    dp[i][j] = dp[i - 1][j]
                else:
                    dp[i][j] = max(dp[i - 1][j], dp[i - 1][j - A[i-1]] + V[i - 1])
        return dp[M - 1][N - 1]

A=[2, 3, 5, 7]
V=[1, 5, 2, 4]
b=Solution().backPackII(10,A,V)
print(b)
解法二: 这里可以使用一维数组进行空间复杂度优化。优化方法为逆序求 result[j] ,优化后的代码如下

class Solution:
    """
    @param m: An integer m denotes the size of a backpack
    @param A: Given n items with size A[i]
    @param V: Given n items with value V[i]
    @return: The maximum value
    """

    def backPackII(self, m, A, V):
        # write your code here
        M = len(A)
        N = m + 1
        dp = [0 for i in range(N) ]

        for i in range(0, M ):
            for j in range(m,-1,-1):
                if j < A[i - 1]:
                    dp[j] = dp[j]
                else:
                    dp[j] = max(dp[j], dp[j - A[i-1]] + V[i - 1])
        return dp[N - 1]

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

猜你喜欢

转载自blog.csdn.net/zlsjsj/article/details/80212143
今日推荐