377. Combination Sum IV

原题如下:

377.Combination Sum IV

Givenan integer array with all positive numbers and no duplicates, find the numberof 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.

题目大意:这道题目意思大概是给定一个没有重复数字的正整数的数组nums以及一个目标整数target,求能够由nums中的元素之和得到target的所有可能的组合。

解题思路:这道题目是一个典型的背包问题,可以用动态规划的方法来解决,定义一个大小为target+1的数组,因为我们要求的是组合的数目,所以状态转移规则是f(i)+=f(i-nums[j]),即数字i的组合数等于所有i-nums[j]的组合数之和,最后我们得到的f(target)就是结果。

算法:

1、       构造一个大小为target+1的数组,初始化为0;

2、       使用二重循环,外层循环的循环次数为target,内层循环的次数为n,n为数组的大小,若是数组中的每一个元素nums[j]小于外循环中的循环次数i,则f(i)+=nums[j],若是相等,则f(i)+=1;

3、       循环结束后,返回f(target)。

算法复杂度分析:整个函数只用了两层循环解决问题,所以最坏复杂度为O(NV),其中N是数组大小,V是target。

具体代码如下:

class Solution {

public:

    int combinationSum4(vector<int>&nums, int target) {

        int n=nums.size();

        if(n==0)return 0;

        vector<int> f(target+1,0);

        for(int i=1;i<=target;i++){

            for(int j=0;j<n;j++){

                if(nums[j]<i)

                f[i]+=f[i-nums[j]];

                else if(nums[j]==i)

                f[i]+=1;

            }

        }

        return f[target];

    }

};

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值