150强访谈中等

目标总和

“目标总和”问题的详细指南和 Python 实现。

问题陈述

中等

给定一个整数数组 nums 和一个整数目标。

您希望通过在 nums 中的每个整数之前添加符号“+”和“-”之一来构建 nums 表达式,然后连接所有整数。

返回您可以构建的不同表达式的数量,其计算结果为目标。

编写一个函数 findTargetSumWays(nums: List[int], target: int) -> int

约束条件
  • 1 <= len(nums) <= 20
  • 0 <= nums[i] <= 1000
  • 0 <= sum(nums) <= 1000
  • -1000 <= target <= 1000

示例

Example 1
Input
nums = [1,1,1,1,1], target = 3
Output
5
Explanation

There are 5 ways: -1+1+1+1+1, +1-1+1+1+1, +1+1-1+1+1, +1+1+1-1+1, +1+1+1+1-1.

Example 2
Input
nums = [1], target = 1
Output
1
Explanation

+1 = 1

Need a Hint?
考虑使用 2D DP 特定的数据结构,例如集合或堆。
Edge Cases to Watch
  • 空输入结构
  • 单元素输入
  • 大数值范围

准备好解决了吗?

Open the problem in PyRun's browser-based Python editor. Your code runs fully offline — no server required.

在编辑器中打开
Found this breakdown helpful?

PyRun is built and maintained by an independent solo developer. If this helped your interview prep, consider buying a coffee!

Buy me a coffee

推荐的 Python 资源

通过相关的交互式教程、备忘单和代码比较来扩展您的知识。