Target Sum

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.

 

Constraints:


Solution:

class Solution {
    Map<Integer, Integer>[] dp;
    
    public int findTargetSumWays(int[] nums, int S) {
        if (S > 1000) return 0;
        dp = new HashMap[nums.length + 1];
        for (int i = 0; i < nums.length + 1; i ++) {
            dp[i] = new HashMap();
        }
        return helper(nums, 0, S, 0);
    }
    
    private int helper(int[] nums, int i, int S, int curr) {
        if (i == nums.length) {
            return curr == S ? 1 : 0;
        }
        if (dp[i].containsKey(curr)) return dp[i].get(curr);
        int res = 0;
        res += helper(nums, i + 1, S, curr - nums[i]);
        res += helper(nums, i + 1, S, curr + nums[i]);
        dp[i].put(curr, res);
        return res;
    }
}