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 資源

透過相關的互動式教學、備忘單和程式碼比較來擴展您的知識。