# Target Sum

## Description

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.

## Solutions

Let $$p$$, $$n$$ be the sums of numbers with positive and negative symbols, respectively. Let $$sum= p +n$$.

$$
\begin{align}
p - n &=S \\
p - n + 2n &= S + 2n \\
p + n &= S + 2n \\
n &= \frac{p+n-S}{2} =\frac{sum - S}{2} \\
p &= sum - n = \frac{sum+S}{2}
\end{align}
$$

Therefore, the problem is equivalent to finding integers that sum up to $$p$$ or finding integers that sum up to $$n$$.

### DFS

Let `dp[i, target]` be the number of subsets of `nums[i..]` that sum up to target.

Then `dp[i, target] = dp[i+1, target] + dp[i+1, target - nums[i]]`.

```cpp
class Solution {
public:
    int findTargetSumWays(vector<int>& nums, int S) {
        int sum = 0;
        for(int num: nums){
            sum += num;
        }
        if(sum < S || (sum - S) % 2) return 0;
        return findTargetSumWays(nums, 0, (sum - S) / 2);
    }
    
    int findTargetSumWays(vector<int> &nums, int i, int target){
        if(target < 0)
            return 0;
        if(i == nums.size())
            return target == 0;
        return findTargetSumWays(nums, i + 1, target) + findTargetSumWays(nums, i + 1, target - nums[i]);
    }
};
```

### Dynamic programming

Let `dp[k, target]` be the number of subsets of `nums[0..k]` that sum up to `target`.

Then `dp[k+1, target] = dp[k, target] + dp[k, target - nums[i]]`.

Since `dp[k+1, :]` depends only on `dp[k, :]`, we can optimize the algorithm to use an array of size `n + 1`, where n is the sum of integers with negative symbol.

```cpp
class Solution {
public:
    int findTargetSumWays(vector<int>& nums, int S) {
        int sum = accumulate(nums.begin(), nums.end(), 0);
        if(sum < S || (sum - S) % 2) return 0;
        int target = (sum - S) / 2;
        vector<int> dp(target + 1, 0);
        dp[0] = 1;
        for(int n : nums)
            for(int i = target; i >= n; --i)
                dp[i] += dp[i - n];
        return dp[target];
    }
};
```

