LeetCode #377 - Combination Sum IV - Medium

Problem

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.

Algorithm

整理一下题意:给定一个没有重复的正整数序列和一个目标整数,在序列中找到一个组合使得组合中所有数的和等于目标整数,要求返回满足要求的组合的数目。注意序列中的元素可以在组合中重复。

与无限背包问题类似,可以看作是给定容量在数组中选择元素的问题。状态转移方程为 f[i]=jf[inums[j]]

考虑一些具体的实现细节。对于初始化的问题,注意每个元素对应的nums[i]本身就构成f[nums[i]]的一种组合,故所有f[nums[i]]初始值应为1。但是由于nums元素的值可能比较大,而f数组的下标可能无法保证f[nums[i]]是有效语句,因此只对在f[i]数组长度内的nums[i]进行初始化。实际上从数学角度考虑,大于target的nums[i]也不能构成组合的一部分,不需要考虑。

代码如下。

//时间复杂度O(n^2)
class Solution {
public:
    int combinationSum4(vector<int>& nums, int target) {
        int n=nums.size();
        vector<int> f(target+1,0);
        for(int i=0;i<n;i++) 
            if(nums[i]<=target)
                f[nums[i]]=1;

        for(int i=0;i<=target;i++){
            for(int j=0;j<n;j++){
                if(i-nums[j]>=0)
                    f[i]+=f[i-nums[j]];
            }
        }
        return f[target];
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值