Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/295.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
python递归方法中最长递增子数组_Python_Recursion_Dynamic Programming - Fatal编程技术网

python递归方法中最长递增子数组

python递归方法中最长递增子数组,python,recursion,dynamic-programming,Python,Recursion,Dynamic Programming,我试着不用递归方法解决这个问题 def findLongest(): nums=[1, 9, 3, 10, 4, 20, 2] f = c = lastMax = p1 = 0 while (p1 < len(nums) - 1): p2 = p1 + 1 while (p2 < len(nums) - 1): if nums[p2] > nums[p1]: c +

我试着不用递归方法解决这个问题

def findLongest():
    nums=[1, 9, 3, 10, 4, 20, 2]
    f = c = lastMax = p1 = 0

    while (p1 < len(nums) - 1):
        p2 = p1 + 1
        while (p2 < len(nums) - 1):
            if nums[p2] > nums[p1]:
                c += 1
                if f == 0:
                    f = 1
                    p1 = p2
            p2 += 1

        if c > lastMax:
            lastMax = c
            f = 0
            c = 0
        p1 += 1
    return lastMax
def findLongest():
nums=[1,9,3,10,4,20,2]
f=c=lastMax=p1=0
而(p1nums[p1]:
c+=1
如果f==0:
f=1
p1=p2
p2+=1
如果c>lastMax:
lastMax=c
f=0
c=0
p1+=1
返回lastMax

我在网上搜索了不少,想找到一种简单易懂的递归方法。

这可以找到列表中最长的单调递增子序列的长度。这不是一个适合递归解决方案的问题

def findLongest(nums):
    last = 99999999
    maxSeq = 0
    for n in nums:
        if n > last:
            seq += 1
            if seq > maxSeq:
                maxSeq = seq
        else:
            seq = 1
        last = n
    return maxSeq
print( findLongest([1, 9, 3, 10, 4, 20, 2]))
这是一个递归版本

def find1(last, nums, n):
    if nums and nums[0] > last:
        return find1(nums[0], nums[1:], n+1 )
    else:
        return n

def findRecursive(nums):
    maxseq = 0
    for i in range(len(nums)):
        n = find1(nums[i], nums[i+1:], 1)
        if n > maxseq:
            maxseq = n
    return maxseq

print( findRecursive([1, 9, 3, 10, 4, 20, 2]))

您是否正在尝试查找列表中按递增顺序排列的最长序列的长度?你的代码生成3,而正确的答案是2。是的,这就是我想做的,谢谢它的工作。。为什么这个问题不能递归地解决?我找到了这个链接,但老实说不明白,我没有说它做不到,我说这不是自然的,这正是评论在链接中所说的。作为一个迭代解决方案,它更有意义。谢谢。我想我看到了递归方法似乎并不自然。