Combination Sum II 解題教學:3 種解法完整比較|LeetCode 40 Best Practice

Combination Sum II 解題教學示意圖|LeetCode 40

本文完整拆解 LeetCode 40 Combination Sum II 的解法:從解題思路、演算法步驟到時間與空間複雜度,並整理邊界情況與 3 種解法比較,幫你把 Combination Sum II 一次弄懂。

Explore diverse LeetCode solutions in Python, C++, JavaScript, SQL, and TypeScript. Ideal for interview prep, learning, and code practice in multiple programming languages. Github Repo Link


Given a collection of candidate numbers (candidates) and a target number (target), find all unique combinations in candidates where the candidate numbers sum to target.

Each number in candidates may only be used once in the combination.

Note: The solution set must not contain duplicate combinations.

Example 1:

Input: candidates = [10,1,2,7,6,1,5], target = 8
Output: 
[
[1,1,6],
[1,2,5],
[1,7],
[2,6]
]

Example 2:

Input: candidates = [2,5,2,1,2], target = 5
Output: 
[
[1,2,2],
[5]
]

Constraints:

  • 1 <= candidates.length <= 100
  • 1 <= candidates[i] <= 50
  • 1 <= target <= 30

Python

				
					# time complexity: O(2^n)
# space complexity: O(n)
from typing import List


class Solution:
    def combinationSum2(self, candidates: List[int], target: int) -> List[List[int]]:
        answer = []
        candidates.sort()
        self.backtrack(candidates, target, 0, [], answer)
        return answer

    def backtrack(self, candidates, target: int, totalIdx: int, path: List[int], answer: List[int]):
        if target < 0:
            return
        if target == 0:
            answer.append(path)
            return
        for i in range(totalIdx, len(candidates)):
            if i > totalIdx and candidates[i] == candidates[i - 1]:
                continue
            self.backtrack(
                candidates,
                target - candidates[i],
                i + 1,
                path + [candidates[i]],
                answer,
            )


candidates = [10, 1, 2, 7, 6, 1, 5]
target = 8
print(Solution().combinationSum2(candidates, target))
				
			

Combination Sum II 解題思路

和 Combination Sum 最大的差別是:每個數字只能用一次,而且候選陣列本身可能有重複值。前者靠「遞迴傳 i+1」解決,後者靠「排序後,同一層跳過與前一個相同的值」解決——同一層選過 2 就不要再選第二個 2,但不同層(也就是路徑上)可以。

Combination Sum II 演算法步驟

  1. 先把 candidates 由小到大排序,讓相同的值相鄰。
  2. 回溯函式從 start 走訪;若 i 大於 start 且 candidates[i] 等於 candidates[i-1] 就 continue,跳過同層重複。
  3. 若 candidates[i] 大於 remain,排序後可直接 break。
  4. 選入後遞迴傳入 i+1,確保每個位置只用一次。

Combination Sum II 複雜度分析

項目複雜度
時間複雜度O(2^n)
空間複雜度O(n)

最壞情況下每個元素都有選與不選兩種可能,時間上界 O(2^n),但排序後的剪枝通常讓實際分支遠少於此。遞迴深度最多 n,空間為 O(n)(不計輸出)。

Combination Sum II 的邊界情況與常見錯誤

  • 去重條件是 i > start 而不是 i > 0,寫錯會把合法的路徑內重複也刪掉。
  • 遞迴要傳 i+1,傳 i 會變成可重複選用。
  • 結果仍要複製 path,否則回溯會破壞已存答案。
  • 候選值若含有 0 或負數,排序剪枝的前提會失效。

Combination Sum II 其他解法比較

解法時間空間說明
先全排列再用集合去重O(n!)O(n!)能跑出正確答案但代價極高
回溯後對結果整體去重O(2^n)O(2^n)浪費在無效分支上
排序 + 同層跳過重複O(2^n)O(n)本文採用