动态规划最长递增子序列问题

本文介绍了一种求解最长递增子序列的算法实现,包括递归版本和动态规划版本,并提供了完整的代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

需要求解的序列是line

IncreasingLine (line[i])表示前 i 个 最大递增子序列。

递归关系式:


1。当 i = 0 时,最长递增序列就是 单个元素line[0]

2。当0  < i < (line.length - 1)  时分两种情况:

      a, 如果 line[i]  >= max (IncreasingLine (line[i -1]))时,则表示当前元素属于最长递增子序列。

       b.否则当前元素不属于最长递增子序列。IncreasingLine (line[i]) = IncreasingLine (line[i -1])。


因此可以写一个简单的递归求解函数:

def Recursive(line,index):
    if index == 0:
        return 1,line[index],line[:1]
    
    n,max,increaseLine = Recursive(line, index-1)
    
    if (line[index] >= max):
        increaseLine.append(line[index])
        return n+1, line[index],increaseLine
    else:
        return n,max,increaseLine
    

def readfile(filename):
    s = []
    file = open(filename,"r")
    char = file.read(1)
    while char:
        if char:
            s.append(char)
            char = char = file.read(1)
    return s

l = readfile('file')

n,max,result = Recursive(l, len(l)-1) 

print(n)
print(result)

这个版本只能解很短的序列,下面是动态规划的版本:

def Recursive(line,index):
    if index == 0:
        return 1,line[index],line[:1]
    
    n,max,increaseLine = Recursive(line, index-1)
    
    if (line[index] >= max):
        increaseLine.append(line[index])
        return n+1, line[index],increaseLine
    else:
        return n,max,increaseLine
    
def Max_increasingLine(line):
    
    count = 0
    result = []
    
    for index in range(len(line)):
        if index == 0:
            count = 1
            result.append(line[index])
            continue
        if line[index] >= max(result):
            count += 1
            result.append(line[index])
    
    return count, result

def readfile(filename):
    s = []
    
    with open("file","r") as file:
        for eachline in file:
            worlds = eachline.split()
            s += worlds
    
    return s

l = readfile('file')

n,result = Max_increasingLine(l)

print(n)
print(result)




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值