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

Combination Sum 解題教學示意圖|LeetCode 39

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

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 an array of distinct integers candidates and a target integer target, return a list of all unique combinations of candidates where the chosen numbers sum to target. You may return the combinations in any order.

The same number may be chosen from candidates an unlimited number of times. Two combinations are unique if the frequency of at least one of the chosen numbers is different.

The test cases are generated such that the number of unique combinations that sum up to target is less than 150 這套工具s for the given input.

Example 1:

Input: candidates = [2,3,6,7], target = 7
Output: [[2,2,3],[7]]
Explanation:
2 and 3 are candidates, and 2 + 2 + 3 = 7. Note that 2 can be used multiple times.
7 is a candidate, and 7 = 7.
These are the only two 該方案s.

Example 2:

Input: candidates = [2,3,5], target = 8
Output: [[2,2,2,2],[2,3,3],[3,5]]

Example 3:

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

Constraints:

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

Python

				
					from typing import List


class Solution:
    def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:
        result = []

        def backtrack(remain: int, comb: List[int], start: int):
            if remain == 0:
                result.append(list(comb))
                return
            elif remain < 0:
                return
            for i in range(start, len(candidates)):
                comb.append(candidates[i])
                backtrack(remain - candidates[i], comb, i)
                comb.pop()

        backtrack(target, [], 0)

        return result
				
			

Combination Sum 解題思路

同一個數字可以重複選用,所以回溯時「不要把索引往後推」是關鍵:選了 candidates[i] 之後,下一層仍從 i 開始,代表可以再選一次同一個數。而為了避免 [2,3] 與 [3,2] 這種同集合不同順序的重複,每一層只能從當前索引往後挑,不能回頭。

Combination Sum 演算法步驟

  1. 先把 candidates 排序,方便後續剪枝。
  2. 定義回溯函式,參數包含起始索引 start、剩餘目標 remain、當前路徑 path。
  3. remain 等於 0 時把 path 的複本放進答案;remain 小於 0 時直接返回。
  4. 從 start 走訪到結尾,若 candidates[i] 大於 remain 可直接 break(排序後的剪枝),否則選入後遞迴呼叫並傳入同一個 i。

Combination Sum 複雜度分析

項目複雜度
時間複雜度O(n^(T/m))
空間複雜度O(T/m)

T 是 target、m 是最小的候選值,遞迴樹的深度最多 T/m,每層最多 n 個分支,所以時間上界是 O(n^(T/m))。遞迴堆疊與路徑長度同樣受 T/m 限制,空間為 O(T/m)(不計輸出)。

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

  • 把 path 放進答案時一定要複製,直接放參考會在回溯後被改掉。
  • 遞迴時傳 i 而不是 i+1,傳錯就變成每個數只能用一次。
  • 排序後的 break 剪枝能大幅加速,但前提是候選值皆為正數。
  • candidates 保證無重複,若有重複要改用 Combination Sum II 的去重寫法。

Combination Sum 其他解法比較

解法時間空間說明
不排序的純回溯O(n^(T/m))O(T/m)正確但缺少剪枝,實測慢很多
完全背包式動態規劃O(n·T)O(T)求數量很快,但要列舉所有組合較麻煩
排序 + 回溯 + 剪枝O(n^(T/m))O(T/m)本文採用