ナップサック問題のコードまとめ(Python)

ナップサック問題

詳しい説明は→ Code Random Thoughtsを参照してください。

最近のいくつかの質問のまとめ
与えられた配列に従ってnums[]、条件を満たす目標値 (目標合計) を求めます。target

从 nums 中找出并返回总和为 target 的元素的最少组合,没有返回-1
数组中的数字不可以重复出现
nums = [1,2,3], target = 6
输出:2
解释:两个3的和为6
(3, 3)
def combinationSum(self, nums: List[int], target: int) -> int:
	dp = [inf] * (target+1)
	dp[0] = 0
	
	for num in nums:
	    for c in range(num , target+1):
	        dp[c] = min(dp[c], dp[c-num ]+1)
	
	ans = dp[target]
	return ans if ans < inf else -1
从 nums 中找出并返回总和为 target 的元素组合的个数(数组元素可以不唯一)
数组中的数字不可以重复出现
nums = [1,2,3], target = 4
输出:4
解释:
(1, 3)
def combinationSum(self, nums: List[int], target: int) -> int:
	dp = [0]*(target+1)
	dp[0] = 1
	
	for num in nums:
	    for c in range(target, num-1, -1):
	        dp[c] += dp[c-num]
	
	return dp[target]
从 nums 中找出并返回总和为 target 的元素组合的个数(数组元素唯一)
数组中的数字可以重复出现,[1 1 2][1 2 1]算一种情况
nums = [1,2,3], target = 4
输出:4
解释:
(1, 1, 1, 1)
(1, 1, 2)
(1, 3)
(2, 2)
def combinationSum(self, nums: List[int], target: int) -> int:
	n = len(nums)
	
	dp = [0] * (target+1)
	dp[0] = 1
	
	for num in nums:
	    for c in range(num, target+1):
	        dp[c] += dp[c-num]
	
	return dp[target]
从 nums 中找出并返回总和为 target 的元素组合的个数(数组元素唯一)
数组中的数字可以重复出现,(1 1 2)(1 2 1)算两种情况
nums = [1,2,3], target = 4
输出:7
解释:
(1, 1, 1, 1)
(1, 1, 2)
(1, 2, 1)
(1, 3)
(2, 1, 1)
(2, 2)
(3, 1)
class Solution:
    def combinationSum(self, nums: List[int], target: int) -> int:
        n = len(nums)

        dp = [0] * (target+1)
        dp[0] = 1

        for i in range(target+1):
            for num in nums:
                if i >= num: dp[i] += dp[i-num]
        
        return dp[target]

おすすめ

転載: blog.csdn.net/weixin_44635198/article/details/130712040