494. 目标和( 记忆化 dfs)
给你一个整数数组 nums
和一个整数 target
。
向数组中的每个整数前添加 '+'
或 '-'
,然后串联起所有整数,可以构造一个 表达式 :
- 例如,
nums = [2, 1]
,可以在2
之前添加'+'
,在1
之前添加'-'
,然后串联起来得到表达式"+2-1"
。
返回可以通过上述方法构造的、运算结果等于 target
的不同 表达式 的数目。
示例 1:
输入:nums = [1,1,1,1,1], target = 3 输出:5 解释:一共有 5 种方法让最终目标和为 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 +1 + 1 + 1 + 1 - 1 = 3
示例 2:
输入:nums = [1], target = 1 输出:1
提示:
1 <= nums.length <= 20
0 <= nums[i] <= 1000
0 <= sum(nums[i]) <= 1000
-1000 <= target <= 1000
class Solution: def findTargetSumWays(self, nums: List[int], target: int) -> int: memo = {} def backtracking(index,cur_cum): key = str(index) + '-' + str(cur_cum) if key in memo: return memo[key] if cur_cum == target and index == len(nums): memo[key] = 1 return 1 if index >= len(nums): memo[key] = 0 return 0 a = backtracking(index+1,cur_cum+nums[index]) b = backtracking(index+1,cur_cum-nums[index]) memo[key] = a+b return a+b return backtracking(0,0)
pos + neg = sum
pos-neg = target
neg = (sum-target)/2
作者:LeetCode-Solution
链接:https://leetcode-cn.com/problems/target-sum/solution/mu-biao-he-by-leetcode-solution-o0cp/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
class Solution { public: int findTargetSumWays(vector<int>& nums, int target) { int sum = 0; for (int& num : nums) { sum += num; } int diff = sum + target; if (diff < 0 || diff % 2 != 0) { return 0; } int n = nums.size(), neg = diff / 2; vector<vector<int>> dp(n + 1, vector<int>(neg + 1)); dp[0][0] = 1; for (int i = 1; i <= n; i++) { int num = nums[i - 1]; for (int j = 0; j <= neg; j++) { dp[i][j] = dp[i - 1][j]; if (j >= num) { dp[i][j] += dp[i - 1][j - num]; } } } return dp[n][neg]; } };
回溯 :
class Solution: def __init__(self): self.res = 0 def findTargetSumWays(self, nums: List[int], target: int) -> int: def backtracking(nums,target,cur,index): key = str(cur) + ',' + str(index) if key in memo: return memo[key] if index == len(nums): if cur == target: return 1 else: return 0 res = 0 res += backtracking(nums,target,cur-nums[index],index+1) res += backtracking(nums,target,cur+nums[index],index+1) memo[key] = res return res memo = {} return backtracking(nums,target,0,0)
class Solution { public: int res = 0; void dfs(vector<int>& nums, int i ,int cur_sum, int target) { if (i == nums.size()) { if (cur_sum == target) { res++; } return; } dfs(nums,i+1,cur_sum+nums[i],target); dfs(nums,i+1,cur_sum-nums[i],target); } int findTargetSumWays(vector<int>& nums, int target) { dfs(nums,0,0,target); return res; } };