Le migliori 150 intervisteFacile

Somma della combinazione

Guida dettagliata e implementazione Python per il problema della "somma delle combinazioni".

Dichiarazione del problema

Facile

Dato un array di candidati interi distinti e un target intero target, restituisce un elenco di tutte le combinazioni univoche di candidati in cui la somma dei numeri scelti dà target. Puoi restituire le combinazioni in qualsiasi ordine.

Lo stesso numero potrà essere scelto tra i candidati un numero illimitato di volte. Due combinazioni sono uniche se la frequenza di almeno uno dei numeri scelti è diversa.

Implementa una funzione combinationSum(candidates: list, target: int) -> list.

Vincoli
  • 1 <= candidates.length <= 30
  • 2 <= candidates[i] <= 40
  • All elements of candidates are distinct
  • 1 <= target <= 40

Esempi

Example 1
Input
[2,3,6,7], 7
Output
[[2,2,3],[7]]
Explanation

2 + 2 + 3 = 7 and 7 = 7. These are the only two combinations.

Example 2
Input
[2,3,5], 8
Output
[[2,2,2,2],[2,3,3],[3,5]]
Explanation

2+2+2+2 = 8, 2+3+3 = 8, and 3+5 = 8.

Example 3
Input
[2], 1
Output
[]
Explanation

No combination of 2's can sum to 1.

Need a Hint?
Prendi in considerazione l'utilizzo di strutture dati specifiche del backtracking 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.