1. 程式人生 > >背包問題2 (lintcode)

背包問題2 (lintcode)

maximum ntc ret pack turn notes class spa with

這裏:

for(int j = 1;j <= m;j++)
result[0][j] = 0x80000000;

不能從0開始,result[0][0]是可以取到的,是0。其他情況取不到才用最小表示。

class Solution {
public:
    /*
     * @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
     
*/ int backPackII(int m, vector<int> &A, vector<int> &V) { // write your code here int length = A.size(); vector<vector<int>> result(length+1,vector<int>(m+1)); for(int i = 0;i <= length;i++) result[i][0] = 0;
for(int j = 1;j <= m;j++) result[0][j] = 0x80000000; for(int i = 1;i <= length;i++){ for(int j = 1;j <= m;j++){ if((j - A[i-1]) >= 0) result[i][j] = max(result[i-1][j-A[i-1]] + V[i-1],result[i-1][j]); else result[i][j]
= result[i-1][j]; } } int max = 0; for(int i = 1;i <= m;i++){ if(result[length][i] > max) max = result[length][i]; } return max; } };

背包問題2 (lintcode)