前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >【leetcode刷题】T170-组合总和 Ⅳ

【leetcode刷题】T170-组合总和 Ⅳ

作者头像
木又AI帮
发布2019-09-25 16:54:45
5020
发布2019-09-25 16:54:45
举报
文章被收录于专栏:木又AI帮木又AI帮

木又连续日更第7天(7/100)

木又的第170篇leetcode解题报告

动态规划类型第15篇解题报告

leetcode第377题:组合总和 Ⅳ

https://leetcode-cn.com/problems/combination-sum-iv/

【题目】

给定一个由正整数组成且不存在重复数字的数组,找出和为给定目标正整数的组合的个数。

代码语言:javascript
复制
示例:
nums = [1, 2, 3]
target = 4
所有可能的组合为:
(1, 1, 1, 1)
(1, 1, 2)
(1, 2, 1)
(1, 3)
(2, 1, 1)
(2, 2)
(3, 1)
请注意,顺序不同的序列被视作不同的组合。
因此输出为 7。

【思路】

使用数组dp[i]来存储满足条件的组合个数,对于nums数组中的元素n,当i > n时,dp[i] = sum(dp[i-n])。

【代码】

python版本

代码语言:javascript
复制
class Solution(object):
    def combinationSum4(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: int
        """
        dp = [0] * (target + 1)
        dp[0] = 1
        for i in range(1, target + 1):
            for n in nums:
                if i >= n:
                    dp[i] += dp[i - n]
        return dp[-1]

C++版本

代码语言:javascript
复制
class Solution {
public:
    int combinationSum4(vector<int>& nums, int target) {
        vector<double> dp(target+1, 0);
        dp[0] = 1;
        for(int i=1; i <= target; i++){
            for(auto n: nums){
                if(i >= n)
                    dp[i] += dp[i - n];
            }
        }
        return dp.back();
    }
};
本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2019-09-23,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 木又AI帮 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档