150強訪談簡單

組合總和

“組合和”問題的詳細指南和 Python 實作。

問題陳述

簡單

給定一組不同的候選整數和一個目標整數目標,傳回候選數的所有唯一組合的列表,其中所選數字總和等於目標。您可以按任何順序返回組合。

可以從候選人中無限次地選擇相同的號碼。如果至少一個所選數字的頻率不同,則兩個組合是唯一的。

實作函數 combinationSum(candidates: list, target: int) -> list

約束條件
  • 1 <= candidates.length <= 30
  • 2 <= candidates[i] <= 40
  • All elements of candidates are distinct
  • 1 <= target <= 40

範例

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?
考慮使用回溯特定的資料結構,例如集合或堆。
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 資源

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