注意j-A[i-1]必须大于等于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] * @return: The maximum size */ int backPack(int m, vector<int> A) { // write your code here int length = A.size(); vector<vector<bool>> result(length+1,vector<bool>(m+1)); for(int i = 0;i <= m;i++) result[0][i] = false; for(int j = 0;j <= length;j++) result[j][0] = true; for(int i = 1;i <= length;i++){ for(int j = 1;j <= m;j++){ if((j-A[i-1]) >= 0) result[i][j] = result[i-1][j-A[i-1]] || result[i-1][j]; else result[i][j] = result[i-1][j]; } } int max = 0; for(int i = 1;i <= length;i++){ for(int j = 1;j <= m;j++){ if(result[i][j] == true){ if(j > max) max = j; } } } return max; } };