# 给定一个非负整数数组,a1, a2, ..., an, 和一个目标数,S。现在你有两个符号 + 和 -。对于数组中的任意一个整数,你都可以从 + 或 -中选# 择一个符号添加在前面。## 返回可以使最终数组和为目标数 S 的所有添加符号的方法数。#### 示例:## 输入:nums: [1, 1, 1, 1, 1], S: 3# 输出:5# 解释:## -1+1+1+1+1 = 3# +1-1+1+1+1 = 3# +1+1-1+1+1 = 3# +1+1+1-1+1 = 3# +1+1+1+1-1 = 3## 一共有5种方法让最终目标和为3。##### 提示:### 数组非空,且长度不会超过 20 。# 初始的数组的和不会超过 1000 。# 保证返回的最终结果能被 32 位整数存下。## Related Topics 深度优先搜索 动态规划# 👍 496 👎 0# leetcode submit region begin(Prohibit modification and deletion)class Solution(object): def findTargetSumWays(self, nums, S): """ :type nums: List[int] :type S: int :rtype: int """ cache = {} def get_res(index, sum): if index == len(nums): if sum == 0: return 1 return 0 if (index, sum) in cache: return cache[(index, sum)] res = get_res(index + 1, sum + nums[index]) + get_res(index + 1, sum - nums[index]) cache[(index, sum)] = res return res return get_res(0, S)# leetcode submit region end(Prohibit modification and deletion)print(Solution().findTargetSumWays([40, 2, 49, 50, 46, 6, 5, 23, 38, 45, 45, 17, 4, 26, 40, 33, 14, 9, 37, 24], 7))