Backpack4-Complete
Example
A solution set is:
[7]
[2, 2, 3]Note
给出 n 个物品,以及一个数组,nums[i] 代表第 i 个物品的大小,保证大小均为正数并且没有重复,正整数 target 表示背包的大小,找到能填满背包的方案数。
注意事项:每一个物品可以使用无数次。Last updated
A solution set is:
[7]
[2, 2, 3]给出 n 个物品,以及一个数组,nums[i] 代表第 i 个物品的大小,保证大小均为正数并且没有重复,正整数 target 表示背包的大小,找到能填满背包的方案数。
注意事项:每一个物品可以使用无数次。Last updated
设 backpack[i][j] 代表前 i 个物品选则若干个,所选物品体积恰为 j 的方案数,则有状态转移方程:
backpack[i][j] = backpack[i - 1][j - k * nums[i]]
backpack[0][0] = 1
backpack[0][i] = 0public class Solution {
/**
* @param nums an integer array and all positive numbers, no duplicates
* @param target an integer
* @return an integer
*/
public int backPackIV(int[] nums, int target) {
// Write your code here
int m = target;
int []A = nums;
int f[][] = new int[A.length + 1][m + 1];
f[0][0] = 1;
for (int i = 1; i <= A.length; i++) {
for (int j = 0; j <= m; j++) {
int k = 0;
while(k * A[i-1] <= j) {
f[i][j] += f[i-1][j - A[i-1] * k];
k += 1;
}
} // for j
} // for i
return f[A.length][target];
}
}