150強訪談簡單

組合總和 II

“Combination Sum II”問題的詳細指南和 Python 實作。

問題陳述

簡單

給定一組候選數字(candidates)和一個目標數字(target),找出候選數字中候選數字總和等於目標數字的所有唯一組合。

候選中的每個數字只能在組合中使用一次。

注意:解決方案集不得包含重複的組合。

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

約束條件
  • 1 <= candidates.length <= 100
  • 1 <= candidates[i] <= 50
  • 1 <= target <= 30

範例

Example 1
Input
[10,1,2,7,6,1,5], 8
Output
[[1,1,6],[1,2,5],[1,7],[2,6]]
Explanation

All unique combinations that sum to 8, using each element at most once.

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

1+2+2 = 5 and 5 = 5. These are the only unique combinations.

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

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