125 · 背包问题(二)Backpack II
描述
有 n 个物品和一个大小为 m 的背包. 给定数组 A 表示每个物品的大小和数组 V 表示每个物品的价值.
问最多能装入背包的总价值是多大?
Example 1:
Input:
m = 10
A = [2, 3, 5, 7]
V = [1, 5, 2, 4]
Output:
9
Explanation:
Put A[1] and A[3] into backpack, getting the maximum value V[1] + V[3] = 9
public 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
*/
public int backPackII(int m, int[] A, int[] V) {
// write your code here
int n = A.length ;
int[][] f = new int[n+1][m+1] ;
f[0][0] = 0 ;
for(int i = 0 ; i <= n ; i++){
for(int j = 0 ; j <= m ; j++){
if(i == 0 || j == 0){
f[i][j] = 0 ;
}else if (A[i-1] > j){
f[i][j] = f[i-1][j] ;
}else{
f[i][j] = Math.max(f[i-1][j] , f[i-1][j-A[i-1]]+V[i-1]) ;
}
}
}
int max = 0 ;
for(int i = 0 ; i <= n ; i++){
for(int j = 0 ; j <= m ; j++){
max = Math.max(f[i][j] , max) ;
}
}
return max ;
}
}