代码随想录算法训练营第46天| 139.单词拆分、关于多重背包,你该了解这些!

代码随想录算法训练营第一天| 704. 二分查找、27. 移除元素

  • 今日学习的文章链接,或者视频链接

第九章 动态规划part08

  • 自己看到题目的第一想法

  • 看完代码随想录之后的想法

139:

完全背包,求排列数,先背包,再物品:

class Solution:
    def wordBreak(self, s: str, wordDict: List[str]) -> bool:
        dp = [False]*(len(s)+1)
        dp[0]=True
        for j in range(1,len(s)+1):
            for i in range(j):
                word = s[i:j]
                if word in wordDict and dp[i]: 
                    dp[j]=True
        return dp[-1]

多重背包:

def test_multi_pack1():
    '''版本一:改变物品数量为01背包格式'''
    weight = [1, 3, 4]
    value = [15, 20, 30]
    nums = [2, 3, 2]
    bag_weight = 10
    for i in range(len(nums)):
        # 将物品展开数量为1
        while nums[i] > 1:
            weight.append(weight[i])
            value.append(value[i])
            nums[i] -= 1
    
    dp = [0]*(bag_weight + 1)
    # 遍历物品
    for i in range(len(weight)):
        # 遍历背包
        for j in range(bag_weight, weight[i] - 1, -1):
            dp[j] = max(dp[j], dp[j - weight[i]] + value[i])
    
    print(" ".join(map(str, dp)))
def test_multi_pack2():
    '''版本:改变遍历个数'''
    weight = [1, 3, 4]
    value = [15, 20, 30]
    nums = [2, 3, 2]
    bag_weight = 10

    dp = [0]*(bag_weight + 1)
    for i in range(len(weight)):
        for j in range(bag_weight, weight[i] - 1, -1):
            # 以上是01背包,加上遍历个数
            for k in range(1, nums[i] + 1):
                if j - k*weight[i] >= 0:
                    dp[j] = max(dp[j], dp[j - k*weight[i]] + k*value[i])

    print(" ".join(map(str, dp)))

  • 自己实现过程中遇到哪些困难

  • 今日收获,记录一下自己的学习时长

你可能感兴趣的:(算法)