原题网址:http://www.lintcode.com/en/problem/backpack/
Given n items with size Ai, an integer m denotes the size of a backpack. How full you can fill this backpack?
Notice
You can not divide any item into small pieces.
Example
If we have 4
items with size [2, 3, 5, 7]
, the backpack size is 11, we can select[2, 3, 5]
, so that the max size we can fill this backpack is 10
. If the backpack size is 12
. we can select [2, 3, 7]
so that we can fulfill the backpack.
You function should return the max size we can fill in the given backpack.
方法:动态规划。将物品逐个放进去,看看有可能达到哪些重量。
public class Solution {
/**
* @param m: An integer m denotes the size of a backpack
* @param A: Given n items with size A[i]
* @return: The maximum size
*/
public int backPack(int m, int[] A) {
// write your code here
boolean[] pack = new boolean[m+1];
Arrays.sort(A);
int max = 0;
pack[0] = true;
for(int i = 0; i < A.length; i++) {
for(int j = Math.min(max, m); j >= 0; j--) {
if (pack[j] && j + A[i] <= m) {
pack[j + A[i]] = true;
max = Math.max(max, j + A[i]);
}
}
}
for(int i = m; i >= 0; i--) {
if (pack[i]) return i;
}
return 0;
}
}