算法题之日常刷题 0003

递归问题的思路:

1:找重复

        1.1:找到一种划分的方法 例如:将一块蛋糕越切越小 将子问题交给下一个函数实现

        1.2:找到一种递推公式 例如:斐波拉契问题的递推公式为 f(n) = f(n-1) + f(n-2)

2:找变化的量

        2.1:变化的量一般作为递推公式的参数

3:找递归的出口

        3.1:递推一定要有出口

题目1:用递归实现插入排序

实现:

#注意一定要注意这个index的下标 这个非常非常重要

def fThree(ls, k):
    if k == 0:
        return
    fThree(ls, k-1)
    index = k-1
    x = ls[k]
    while x < ls[index] and index >=0:
        ls[index+1] = ls[index]
        index -= 1
    ls[index+1] = x
if __name__ == "__main__":
    ls = [7, 4, 8, 9, 3, 2, 4, 4, 2]
    fThree(ls, 8)
    print(ls)

猜你喜欢

转载自blog.csdn.net/qq_50709355/article/details/123345099