LeetCode 377. Combination Sum IV

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.  

分析

这道题用动态规划,采用自底向上的方法,for(int i=1;i<=target;i++), 然后对nums中的每个数n, 如果n<i, 那么dp[i]=dp[i-n] ,如果n==i,那么dp[i]++; 如果n>i,什么也不做。

这道题可以和LeetCode 494. Target Sum 做比较都是从一个给定的数集中选取一定的数来求和等于目标数,当不同的是,这道题给定的数集中的数是没有使用次数限制的,而那个是数集中的每个数都只能用一次。

class Solution {
public:
    int combinationSum4(vector<int>& nums, int target) {
        vector<int> dp(target+1,0);
        for(int i=1;i<=target;i++)
            for(auto n:nums){
                if(n<i)
                   dp[i]+=dp[i-n];
                else if(n==i)
                   dp[i]++;
            }        
        return dp[target];
    }
};
原文地址:https://www.cnblogs.com/A-Little-Nut/p/10061272.html