BackPack 5
Solution
[1, 2, 5, 6] S = 10
0-1硬币,构成背包为10的方案数。
dp[i][j] = dp[i-1][j] + dp[i-1][j-A[i]]
Code
/**
* @param nums an integer array and all positive numbers
* @param target an integer
* @return an integer
*/
int backPackV(vector<int>& nums, int target) {
// Write your code here
int n = nums.size();
if(n == 0)
{
return 0;
}
vector<vector<int>> dp;
for(int i = 0; i < 2; i++)
{
vector<int> tmp(target+1, 0);
tmp[0] = 1;
dp.push_back(tmp);
}
for(int i = 1; i < n+1; i++)
{
for(int j = 0; j < target+1; j++)
{
dp[i%2][j] = dp[(i-1)%2][j];
if(j >= nums[i-1])
{
dp[i%2][j] += dp[(i-1)%2][j-nums[i-1]];
}
}
}
return dp[n%2][target];
}