总结几个网上关于动态规划的经典例题,用python实现
1.入门:
凑硬币:用1,3,5面值的硬币凑i元,最少需要几个硬币
#author:xinxinzhang
n=12#凑11元
total=[i for i in range(n)]
v=[1,3,5]
for i in range(1,n):
for j in v:
if j<=i and (total[i-j]+1)<total[i]:#选比不选好
total[i]=total[i-j]+1
print(total[-1])
2.初级:
求最长非降子序列长:
#author:xinxinzhang
def lis(arr):
d = [1] * len(arr)
len_num = len(arr)
for i in range(1,len_num):
for j in range(i):
if arr[j] <= arr[i] and d[i]<d[j]+1:#max{1,d[j]for j in range(i)+1}保证非降需 且取前面非降序长度最大的:
d[i] = d[j] + 1
if d[i] > len_num:
d[i]=len_num
return d[-1]
print(lis([3,2,1,5]))
持续更新。。