1.贪心算法,找零问题
# greedy algorithm money = [100,50,20,5,1] def change_money(x): change = [0,0,0,0,0] for i,m in enumerate(money): change[i] = x // money[i] x = x % money[i] if x > 0: print("还剩%s" % x) return change print(change_money(356.2))
2.贪婪算法:数字拼接问题
3.动态规划:最长上升子序列
3.动态规划:最长公共字符串
def fib(n):
'''斐波那契数列'''
f = [1,1]
for i in range(2, n+1):
f.append(f[-1]+f[-2])
print(f)
return f[n]
fib(5)
def LIS(x):
'''最长公共子序列'''
F = [0 for _ in range(len(x))]
p = [-1 for _ in range(len(x))]
# 初始化
F[0] = 1
p[0] = -1
for k in range(1, len(F)):
max_loc = -1
max_num = 0
# 内层循环表示F[0:k]里所有小于x[k]的对应位置的F[i]的最大值
for i in range(0, k):
if x[i] < x[k]:
if F[i] > max_num:
max_loc = i
max_num = F[i]
F[k] = max_num + 1
p[k] = max_loc
max_i = 0
for i in range(1,len(F)):
if F[i] > F[max_i]:
max_i = i
lis = []
i = max_i
while i >= 0:
lis.append(x[i])
i = p[i]
lis.reverse()
return lis
print(LIS([9,7,2,8,3,5,2]))
def LCS(x, y):
# 最长公共子序列(二维)
F = [[0 for _ in range(len(y)+1)] for _ in range(len(x)+1)]
p = [[0 for _ in range(len(y)+1)] for _ in range(len(x)+1)]
for i in range(1, len(x)+1):
p[i][0] = 2
for j in range(1, len(y)+1):
p[0][j] = 1
# 0 斜向 1 横向 j-1 2竖向 i-1
for i in range(1, len(x)+1):
for j in range(1, len(y)+1):
if x[i-1] == y[j-1]:
F[i][j] = F[i-1][j-1]+1
p[i][j] = 0
else:
#F[i][j] = max(F[i-1][j], F[i][j-1])
if F[i-1][j] > F[i][j-1]:
F[i][j] = F[i-1][j]
p[i][j] = 2
else:
F[i][j] = F[i][j-1]
p[i][j] = 1
lcs = []
i = len(x)
j = len(y)
while i > 0 or j > 0:
if p[i][j] == 0:
lcs.append(x[i-1])
i -= 1
j -= 1
elif p[i][j] == 1:
j -= 1
else:
i -= 1
lcs.reverse()
return lcs
#return F[i][j]
print(LCS("ABBCBDE", "DBBCDB"))
def LCSS_BF(x,y):
# 最长公共字符串(暴力)
m = len(x)
n = len(y)
max_len = 0
max_str = ""
for k in range(0, min(m,n)):
for i in range(0, m-k+1):
for j in range(0, n-k+1):
if x[i:i+k] == y[j:j+k]:
if k > max_len:
max_len = k
max_str = x[i:i+k]
return max_str
print(LCSS_BF("ABBCBDE", "DBBCDB"))
def LCSS(x, y):
# 最长公共字符串
F = [[0 for _ in range(len(y)+1)] for _ in range(len(x)+1)]
p = [[0 for _ in range(len(y)+1)] for _ in range(len(x)+1)]
# 0 不匹配 1匹配
for i in range(1, len(x)+1):
for j in range(1, len(y)+1):
if x[i-1] == y[j-1]:
F[i][j] = F[i-1][j-1]+1
p[i][j] = 1
else:
F[i][j] = 0
p[i][j] = 0
max_val = 0
max_i = 0
max_j = 0
for i in range(1, len(x)+1):
for j in range(1, len(y)+1):
if F[i][j] > max_val:
max_val = F[i][j]
max_i = i
max_j = j
#tracback
lcss = []
i = max_i
j = max_j
while p[i][j] == 1:
lcss.append(x[i-1])
i -= 1
j -= 1
lcss.reverse()
return lcss
print(LCSS("ABBCBDE", "DBBCDB"))