Backpack II 解题报告

来源:互联网 发布:有注入漏洞的网站源码 编辑:程序博客网 时间:2024/05/29 11:33

Backpack II

Description

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?

Notice

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

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.

Challenge

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

实现思路

和Backpack 解题报告 背包问题深入浅出
的区别在于,物品的空间和价值分离出来了,但求解思路是类似的,具体背包问题求解原理可参考这一篇文章,这一题只需要在上一体的基础上做小小变动即可.

用简化后的模型,dp[k]表示放入第i件物品(i=0…A.length)的最大价值。
假设重量数组A是有序的,我们可以通过j->[m…A[i]],利用公式
dp[j] = Math.max(dp[j], dp[j-A[i]] + V[i]);求出在有j的重量容量下,最优的背包价值,而对于j<A[i]部分,根据迭代规律,默认就是上一层的值,等效于背包问题1中的dp[i][j] = dp[i-1][j]
通过以上分析,结合我们对上一篇文章背包问题1的理解,可快速写出下列简洁代码。

/** * @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] * @return: The maximum value */public int backPackII(int m, int[] A, int V[]) {    int n = A.length;    int dp[] = new int[m+1];    for(int i = 0 ; i < n ; i ++){        for(int j = m ; j >= A[i] ; j --){            dp[j] = Math.max(dp[j], dp[j-A[i]] + V[i]);        }    }    return dp[m];}
0 0
原创粉丝点击