HackerRank

Classic DP, and requires you to track optimal path.

len1, len2 = map(int, raw_input().strip().split())

a = map(int, raw_input().strip().split())
b = map(int, raw_input().strip().split())

rec= [[(-1, (-1, -1)) for x in range(len1 + 1)] for x in range(len2 + 1)] 
dp = [[0 for x in range(len1 + 1)] for x in range(len2 + 1)] 
for i in range(1,len1 + 1):
    for j in range(1,len2 + 1):
        if i * j == 0:
            dp[j][i] = 0
            continue
        if a[i - 1] == b[j - 1]:
            dp[j][i] = dp[j - 1][i - 1] + 1
            rec[j][i] = (a[i - 1], (j - 1, i - 1))
        else:
            dp[j][i] = max(dp[j - 1][i], dp[j][i - 1])
            if dp[j - 1][i] >= dp[j][i - 1]:
                rec[j][i] = (-1, (j - 1, i))
            else:
                rec[j][i] = (-1, (j, i - 1))
#print dp[len2][len1]            

ret = []
tmp = rec[len2][len1]
while tmp[-1][-1] != -1:
    if tmp[0] != -1:
        ret.append(tmp[0])
    tmp = rec[tmp[-1][0]][tmp[-1][1]]
ret.reverse()

print (' '.join(map(str, ret)))
原文地址:https://www.cnblogs.com/tonix/p/4355495.html