-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtarget_sum.py
25 lines (22 loc) · 976 Bytes
/
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
from typing import List
class TargetSum:
def findTargetSumWays(self, nums: List[int], target: int) -> int:
# Special case
if not nums:
return 0
# Dictionary to keep track of overlapping subproblems
lookup = dict()
return self.evaluate(nums, target, 0, lookup)
def evaluate(self, nums: List[int], target: int, index: int, lookup: dict):
# Base case
if index >= len(nums):
return 1 if target == 0 else 0
# Found the already evaluated solution
key = str(index) + "-" + str(target)
if key in lookup:
return lookup[key]
# Evaluate for both positive and negative signs
ways = self.evaluate(nums, target - nums[index], index + 1, lookup) + self.evaluate(nums, target + nums[index],
index + 1, lookup)
lookup[key] = ways
return ways