题目:
思路:
- 深度优先法
代码:
class Solution:
def findTargetSumWays(self, nums: List[int], S: int) -> int:
visited = {}
def DFS(index, res):
if index < len(nums) and (index, res) not in visited:
visited[(index, res)] = DFS(index+1, res+nums[index]) + DFS(index+1, res-nums[index])
return visited.get((index, res), int(res == S))
return DFS(0, 0)