You are given a list of non-negative integers, a1, a2, ..., an, and a target, S. Now you have 2 symbols ​​+​​​ and ​​-​​​. For each integer, you should choose one from ​​+​​​ and ​​-​​ as its new symbol.

Find out how many ways to assign symbols to make sum of integers equal to target S.

Example 1:

Input: nums is [1, 1, 1, 1, 1], S is 3. 
Output: 5
Explanation:

-1+1+1+1+1 = 3
+1-1+1+1+1 = 3
+1+1-1+1+1 = 3
+1+1+1-1+1 = 3
+1+1+1+1-1 = 3

There are 5 ways to assign symbols to make the sum of nums be target 3.

Note:

  1. The length of the given array is positive and will not exceed 20.
  2. The sum of elements in the given array will not exceed 1000.
  3. Your output answer is guaranteed to be fitted in a 32-bit integer.

题解:

典型01背包问题,每个数是加还是减。

有更巧妙的方法是计算正负sum(+)和sum(-),sum(+) + sum(-) = sum,sum(+) - sum(-) = S,然后得到sum + S = 2 * sum(+)必为偶数,然后找到sum(+)的个数即可,这样就不需要二维动态规划数组了。

class Solution {
public:
int findTargetSumWays(vector<int>& nums, int S) {
int n = nums.size();
int sum = 0;
for (int i = 0; i < n; i++) {
sum += nums[i];
}
if (sum < S || -sum > S) {
return 0;
}
vector<vector<int>> dp(n + 1, vector<int>(sum + sum + 1, 0));
dp[0][sum] = 1;
for (int i = 1; i <= n; i++) {
for (int j = 0; j <= sum + sum; j++) {
if (j + nums[i - 1] < sum + sum + 1) {
dp[i][j] += dp[i - 1][j + nums[i - 1]];
}
if (j - nums[i - 1] >= 0) {
dp[i][j] += dp[i - 1][j - nums[i - 1]];
}
}
}
return dp[n][sum + S];
}
};