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:
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.
Solutions
Let , be the sums of numbers with positive and negative symbols, respectively. Let .
Therefore, the problem is equivalent to finding integers that sum up to or finding integers that sum up to .
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]]
.
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.
Last updated