Given an array of distinct integers nums and a target integer target, return the number of possible combinations that add up to target.

The test cases are generated so that the answer can fit in a 32-bit integer.

Example 1:

Input: nums = [1,2,3], target = 4 Output: 7 Explanation: The possible combination ways are: (1, 1, 1, 1) (1, 1, 2) (1, 2, 1) (1, 3) (2, 1, 1) (2, 2) (3, 1) Note that different sequences are counted as different combinations. Example 2:

Input: nums = [9], target = 3 Output: 0

解題思路:

問題主要是要找出能組成 target 的組合數。

一開始看到題目的時候其實只想到暴力破解法,但重新排列組合後發現有些端倪可以做。

其實第一個 Example 就可以找到規律

[1, 1, 1, 1]  -- 1 + 加起來是3的組合
[1, 1, 2]     .
[1, 2, 1]     .
[1, 3]        .
[2, 1, 1]     -- 2 + 加起來是2的組合
[2, 2]        .
[3, 1]        -- 3 + 加起來是1的組合

在其中 1 + 加起來是3的組合3的組合 又可以分割成 1 + 加起來是2的組合2 + 加起來是1的組合,是不是很像 費氏數列的概念。

所以我們可以使用動態規劃來解題

Code Example

class Solution:
    def combinationSum4(self, nums: List[int], target: int) -> int:
        dp = [0 for i in range(target+1)]

        for i in range(1, target+1):
            for num in nums:
                if i < num:
                    continue
                if num == i: ## 自己則 +1
                    dp[i] += 1
                if dp[i-num] > 0: ## i + 加起來是 num 的組合,如果有的話
                    dp[i] += dp[i-num]
        return(dp[-1])