We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Difficulty: 中等
Related Topics: 数组, 动态规划, 回溯
给你一个整数数组 nums 和一个整数 target 。
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
Language: JavaScript
/** * @param {number[]} nums * @param {number} target * @return {number} */ // 回溯 var findTargetSumWays = function(nums, target) { let count = 0 const backtrack = (nums, target, index, sum) => { if (index === nums.length) { if (sum === target) { count++ } } else { backtrack(nums, target, index+1, sum + nums[index]) backtrack(nums, target, index+1, sum - nums[index]) } } backtrack(nums, target, 0, 0) return count };
The text was updated successfully, but these errors were encountered:
No branches or pull requests
494. 目标和
Description
Difficulty: 中等
Related Topics: 数组, 动态规划, 回溯
给你一个整数数组
nums
和一个整数target
。向数组中的每个整数前添加
'+'
或'-'
,然后串联起所有整数,可以构造一个 表达式 :nums = [2, 1]
,可以在2
之前添加'+'
,在1
之前添加'-'
,然后串联起来得到表达式"+2-1"
。返回可以通过上述方法构造的、运算结果等于
target
的不同 表达式 的数目。示例 1:
示例 2:
提示:
1 <= nums.length <= 20
0 <= nums[i] <= 1000
0 <= sum(nums[i]) <= 1000
-1000 <= target <= 1000
Solution
Language: JavaScript
The text was updated successfully, but these errors were encountered: