-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path494.target-sum.py
65 lines (51 loc) · 1.19 KB
/
494.target-sum.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
# Level: Medium
# TAGS: Dynamic Programming
import collections
from typing import List
class Solution:
"""
DP Top-Down
Time and Space: O(N*T)
"""
def findTargetSumWays(self, nums: List[int], target: int) -> int:
memo = {}
def dfs(i, total):
if i == len(nums):
# is this the way to add/sub an item
return 1 if total == target else 0
if (i, total) in memo:
return memo[(i, total)]
add = dfs(i + 1, total + nums[i])
sub = dfs(i + 1, total - nums[i])
return add + sub
return dfs(0, 0)
"""
DP Bottom-Up
Time: O(N*T)
Space: O(T)
"""
def findTargetSumWays2(self, nums: List[int], target: int) -> int:
dp = {0: 1}
for num in nums:
nxt = collections.defaultdict(int)
for total in dp:
nxt[total + num] += dp[total]
nxt[total - num] += dp[total]
dp = nxt
return dp[target]
tests = [
(
(
[1, 1, 1, 1, 1],
3,
),
5,
),
(
(
[1],
1,
),
1,
),
]