Backpack III

Description

Given n kinds of items, and each kind of item has an infinite number available. The i-th item has size A[i] and value V[i].

Also given a backpack with size m. What is the maximum value you can put into the backpack?

  1. You cannot divide item into small pieces.
  2. Total size of items you put into backpack can not exceed m.

Example

Example 1:

Input: A = [2, 3, 5, 7], V = [1, 5, 2, 4], m = 10
Output: 15
Explanation: Put three item 1 (A[1] = 3, V[1] = 5) into backpack.

Example 2:

Input: A = [1, 2, 3], V = [1, 2, 3], m = 5
Output: 5
Explanation: Strategy is not unique. For example, put five item 0 (A[0] = 1, V[0] = 1) into backpack.
思路:

类似于最基本的01背包, 我们设定 f[i][j] 表示前 i 种物品装到容量为 j 的背包里, 能获取的最大价值为多少.

比较简单的转移是直接枚举第i种物品取用多少个: f[i][j] = max{f[i - 1][j - x * A[i]] + x * V[i]}

但是这样速度较慢, 可以优化成 f[i][j] 直接由 f[i][j - A[i]] 转移, 并且从小到大枚举 j, 这样做的含义就是在已经拿过第 i 个物品的之后还可以再拿它. 也就是说: 计算 f[i][j] 时, 初始设置为 f[i - 1][j], 然后 f[i][j] = max(f[i][j], f[i][j - A[i]] + V[i])

另外, 可以使用滚动数组优化, 使用滚动数组之后也不必要手动设置 f[i][j] = f[i - 1][j], 与01背包使用的滚动数组相反, 这里恰好需要正着枚举容量 j, 因而有 f[j] = max(f[j], f[j - A[i]] + V[i])

public class Solution {
    /**
     * @param A: an integer array
     * @param V: an integer array
     * @param m: An integer
     * @return: an array
     */
   public int backPackIII(int[] A, int[] V, int m) {
        // Write your code here
        int n = A.length;
        int[] f = new int[m + 1];
        for (int i = 0; i < n; ++i)
            for (int j = A[i]; j <= m; ++j)
                if (f[j - A[i]] + V[i] > f[j])
                    f[j] = f[j - A[i]] + V[i];
        return f[m];
    }
}

  

猜你喜欢

转载自www.cnblogs.com/FLAGyuri/p/12078438.html
今日推荐