记录一下最近遇到的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))