码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode 377. Combination Sum IV

时间:2018-12-03 22:58:00      阅读:245      评论:0      收藏:0      [点我收藏+]

标签:cat   and   tar   www.   .com   target   hat   https   http   

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

LeetCode 377. Combination Sum IV

标签:cat   and   tar   www.   .com   target   hat   https   http   

原文地址:https://www.cnblogs.com/A-Little-Nut/p/10061272.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!