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());

        vectorlong 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];
        
    }
};

 

你可能感兴趣的:(leetcode377 - Combination Sum IV - medium)