1. 程式人生 > 實用技巧 >leetcode377 - Combination Sum IV - medium

leetcode377 - Combination Sum IV - medium

Given an integer array with all positive numbers and no duplicates, find the number of possible combinations that add up to a positive integer target.

Example:

nums = [1, 2, 3]
target = 4

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.

Therefore the output is 7
.

Follow up:
What if negative numbers are allowed in the given array?
How does it change the problem?
What limitation we need to add to the question to allow negative numbers?

繼續用backtracking的話會TLE。因為只要返還結果的數量,這裡用dp來做。

dp[i]表示target為i時有多少個combinations。dp[0]=1,可以想成是所有數都得是0個,所以結果是1種。 從target=1開始考慮,對於每個target,遍歷nums,對於當前的數num,如果某個數x加上num等於target的話,那就是一種組合方式。所以有多少種方式到target-num,就有多少種方式到target。

小小的優化:先sort nums,每次遍歷nums的時候,如果當前target < 當前num, 那針對這個target,後面的num都不用掃了,肯定都不用考慮的,趕緊去下一個target比。對於最後的target很大但nums裡數很分散的情況會有幫助。

leetcode OJ裡用int會overflow,還至少要用到unsigned long long才行

實現:

class Solution {
public:
    int combinationSum4(vector<int>& nums, int target) {
        
        sort(nums.begin(), nums.end());

        vector
<unsigned long long int> dp(target+1, 0); dp[0] = 1; for (int i=1; i<=target; i++){ for (int num : nums){ if (i < num) break; dp[i] += dp[i-num]; } } return dp[target]; } };