48 leetcode - Combination Sum IV

本文探讨了组合总和IV问题的两种解决方法:暴力法和动态规划法。暴力法虽然直观但容易超时;动态规划法则通过构建状态转移方程有效解决了该问题。文章最后给出了详细的动态规划实现代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

暴力法,但是超时了…

#!/usr/bin/python
# -*- coding: utf-8 -*-
'''
Combination Sum IV
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.
'''
class Solution(object):
    times = 0
    def combinationSum4(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: int
        """
        length = len(nums)
        if length == 0:
            return 0
        Solution.times = 0
        nums.sort()
        self.__combinationSum4(nums,length,target,0)
        return Solution.times

    def __combinationSum4(self,nums,length,target,sum):
        if sum == target:
            Solution.times += 1
            return 0
        if sum > target:
            return 0

        for i in range(0,length):
            self.__combinationSum4(nums,length,target,sum + nums[i]) 

if __name__ == "__main__":
    s = Solution()
    print s.combinationSum4([1,2,4],32)

动态规划

class Solution(object):
    def combinationSum4(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: int
        """
        length = len(nums)
        if length == 0:
            return 0

        nums.sort()
        dp = [0] * (target+1)

        for i in range(target + 1):
            for val in nums:
                if val > i:
                    break

                if val == i:
                    dp[i] += 1
                    break

                dp[i] += dp[i - val]
        return dp[target]

不懂的话可以参考(http://www.cnblogs.com/grandyang/p/5705750.html).

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值