leetcode|494.目标和 python3

题目: 【leetcode|494.目标和 python3】leetcode|494.目标和 python3
文章图片

思路:

  • 深度优先法
代码:
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)

    推荐阅读