Le migliori 150 intervisteMedio

Somma obiettivo

Guida dettagliata e implementazione Python per il problema 'Target Sum'.

Dichiarazione del problema

Medio

Ti viene fornito un array di numeri interi e un target intero.

Vuoi creare un'espressione a partire dai numeri aggiungendo uno dei simboli "+" e "-" prima di ogni numero intero in numeri e quindi concatenare tutti i numeri interi.

Restituisce il numero di espressioni diverse che puoi creare, che restituisce il target.

Scrivi una funzione findTargetSumWays(nums: List[int], target: int) -> int.

Vincoli
  • 1 <= len(nums) <= 20
  • 0 <= nums[i] <= 1000
  • 0 <= sum(nums) <= 1000
  • -1000 <= target <= 1000

Esempi

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?
Prendi in considerazione l'utilizzo di strutture dati specifiche per DP 2D come set o heap.
Edge Cases to Watch
  • Strutture di input vuote
  • Ingressi a elemento singolo
  • Grandi limiti numerici

Pronto a risolvere?

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

Apri nell'editor
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

Risorse Python consigliate

Espandi le tue conoscenze con tutorial interattivi, foglietti illustrativi e confronti di codici correlati.