Combination Sum IV

一开始以为这道题是背包DP,做了半天发现不对,背包问题在数组有序的情况下是不会计算出现2,1,1这种大数在前的组合的,最后发现其实还是一个简单的序列型DP,类似LIS的情况

class Solution(object):
    def combinationSum4(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: int
        """
        nums.sort()
        n = len(nums)
        dp = [0] * (target + 1)
        dp[0] = 1

        for i in xrange(1, target + 1):
            for num in nums:
                if i >= num:
                    dp[i] += (dp[i - num])
                else:
                    break

        return dp[target]

results matching ""

    No results matching ""