//注意初始化的时候,如果nums[0]为0,则重复初始化,导致只计算一次,因此后来改成+=,而不是直接赋值
class Solution {
public:
int findTargetSumWays(vector
int sum = 0;
for (auto n : nums) sum += n;
if (S > sum || S < -sum || nums.size() == 0) return 0;
vector
dp[0][nums[0] + sum] += 1;
dp[0][-nums[0] + sum] += 1;
for (int i = 1; i < nums.size(); i++) {
for (int j = 0; j < 2 * sum + 1; j++) {
if (j - nums[i] >= 0) dp[i][j] += dp[i - 1][j - nums[i]];
if (j + nums[i] < 2 * sum + 1) dp[i][j] += dp[i - 1][j + nums[i]];
}
}
return dp.back()[S + sum];
}
};