# 494. 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.

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

# Solution

Approach 1: brute force -- backtracking. Time: O(2^N).

Approach 2: DP with a 2D table recording the index and the number of ways to sum to the total.

# Code (Python)

Approach 1:

    def findTargetSumWays(self, nums: List[int], S: int) -> int:
        # brute force in O(N * 2^N) -- TLE
        '''count = 0
        for combination in range(2 ** len(nums)):
            total = 0
            for i in range(len(nums)):
                multiplier = 1 if (combination >> i) & 1 == 1 else -1
                total += nums[i] * multiplier
            if total == S:
                count += 1
        return count'''
        
        # brute force (backtracking) in O(2^N) -- TLE
        count = [0]
        self._target_sum(0, S, nums, count)
        return count[0]
    
    def _target_sum(self, index, target, nums, count):
        if index == len(nums):
            if target == 0:
                count[0] += 1
        else:
            self._target_sum(index + 1, target - nums[index], nums, count)
            self._target_sum(index + 1, target + nums[index], nums, count)

Approach 2:

    def findTargetSumWays(self, nums: List[int], S: int) -> int:
        # idea: same recursion with 2D memoization, because there are duplicate calculations with same index and target
        # result[i][total] represents the number of ways for the first i items to sum up to 'total'
        # need to offset the sum value by adding sum(nums) so that the index value is always positive in the table
        offset = sum(nums)
        if S > offset or S < -offset:
            return 0
        # the sum ranges from -offset to +offset, including 0
        table = [[0 for _ in range(2 * offset + 1)] for _ in range(len(nums) + 1)]
        
        # the first 0 items add up to 0
        table[0][0+offset] = 1
        
        for i in range(1, len(table)):
            for s in range(len(table[0])):
                if table[i-1][s] != 0:
                    # offset is already accounted for
                    table[i][s-nums[i-1]] += table[i-1][s]
                    table[i][s+nums[i-1]] += table[i-1][s]
        return table[-1][S+offset]
        # can reduce a dimension because we're using only the previous row

# Code (C++)

Approach 1:

Approach 2: