494.目标和 python3

题目:

494.目标和 python3_第1张图片

思路:

  • 深度优先法

代码:

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)
            

你可能感兴趣的:(leetcode,题目)