标签:
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?
和上一题差不多,这题里动态规划用的数组类型是int[],用来记录背包里放容积为k的物体时,这些物体的最大价值
public class Solution { /** * @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[]) { // write your code here if(A == null || A.length == 0) return 0; int[] dp = new int[m + 1]; int result = 0; dp[0] = 0; for(int i = 0; i < A.length; i++){ for(int j = m ; j >= A[i]; j--){ dp[j] = Math.max(dp[j], dp[j - A[i]] + V[i]); } } for(int i = 0; i < dp.length; i++){ if(dp[i] > result) result = dp[i]; } return result; } }
标签:
原文地址:http://www.cnblogs.com/goblinengineer/p/5275761.html