class Solution {
public:
int findTargetSumWays(vector<int>& nums, int target) {
int sum = 0;
for (int i = 0; i < nums.size(); i++) {
sum += nums[i];
}
// left - (sum - left) = target
// left = (sum + target) / 2
if (abs(target) > sum) return 0;
if ((sum + target) % 2 == 1) return 0;
// 背包需装的大小
int bagsize = (sum + target) / 2;
vector<int> dp(bagsize + 1, 0);
// j下标代表装的大小,dp[j]代表装下容量j的方法数
dp[0] = 1;
for (int i = 0; i < nums.size(); i++) {
for (int j = bagsize; j >= nums[i]; j--) {
dp[j] += dp[j - nums[i]];
}
}
return dp[bagsize];
}
};
总结
- 装满背包,递推公式dp[j] += dp[j - nums[i]];