【Leetcode】377. Combination Sum IV 377. 组合总和 Ⅳ

【Leetcode】377. Combination Sum IV 377. 组合总和 Ⅳ

解法

参考:https://leetcode-cn.com/problems/combination-sum-iv/comments/18400

518. Coin Change 2类似,不过那题是无序的多重背包
本题是有序的多重背包
答案也是非常类似的,和518. Coin Change 2的区别就是把循环前后换一遍,非常神奇
代码如下:

class Solution(object):
    def combinationSum4(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: int
        """
        if target<=0:
            return []
        f = [0]*(target+1)
        f[0] = 1
        nums.sort()
        for s in xrange(1,target+1):
            for c in nums:
                if s>=c:
                    f[s] += f[s-c]
                else:
                    break
        return f[target]

为什么可以达到有序的效果呢?
f[i]的值表示的是和为i的不同序列的个数
f[i] += f[i-nums[j]]
表示在那些和为f[i-nums[j]的序列后面添加nums[j]来得到新的序列,由于nums[j]各不相同,所以f[i-nums[j]得到的序列是不相交的