leetcode494

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.

Idea

counting problems, max min problems are always involved with DP.

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Solution(object):
def findTargetSumWays(self, nums, S):
"""
:type nums: List[int]
:type S: int
:rtype: int
"""
# cache[(i, s)] the number of combination sum up to s from nums[i] to nums[n - 1]
def findTarget(i, s):
if (i, s) not in cache:
r = 0
if i == len(nums): # base case
if s == 0: # the top of the figure, where number of solutions is 1.
r = 1
else:
r = findTarget(i+1, s-nums[i]) + findTarget(i+1, s+nums[i])
cache[(i, s)] = r
return cache[(i, s)]
cache = {}
return findTarget(0, S)