dp问题1:钢条切割问题

记录一下最近遇到的dp问题,瞎写

dp钢条切割问题:将长为n的钢条,切割成m段,不同长度的钢条市场价格不同,切割本身没有成本,求最大价值的切割方案
其中prices是钢条的价格,lens是每一个钢条的长度,n是待切割的总长度

#lens长度:1,2,3,4,5,6,7,8,9,10
#prices价格:1,5,8,16,10,17,17,20,24,30 
#解决方法1——朴素递归法(暴力法)
def help(prices, lens, n):
    if n == 0:
        return 0
    if n < 0:
        return float('-inf') 
    ans = 0
    size = len(lens)
    for i in range(size):
        ans = max(ans, prices[i] + help(prices, lens, n - lens[i]))
    return ans
#解决方法2——动态规划,减少不必要的重复计算
def dp(prices, lens, n):
    dp = [float('-inf')] * (n+1)
    dp[0] = 0
    for i in range(1, n+1):
        for j in range(len(lens)):
            if i < lens[j]:
                continue
            dp[i] = max(dp[i], prices[j] + dp[i - lens[j]])

    return dp[n]



prices = [1,5,8,16,10,17,17,20,24,30]
lens = [1,2,3,4,5,6,7,8,9,10]
print(dp(prices, lens, 10))

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值