• 剑指offer python版 剪绳子


    def rope_cut(length):
        # 最优解数组,当长度为0是为0,当长度为1是为1,当长度为2时为2,当长度大于3时,3就不能切开了,因为3>1*2,最优解数组为3
        li=[0,1,2,3]
        if length==0:#当长度为0时,返回0
            return 0
        if length==1:#当长度为1时,返回1
            return 1
        if length==2:#当长度为2时,返回2
            return 2
        if length==3:#当长度为3时,返回2,虽然最优解数组里为2,但是每次必须得切一刀,这样1*2=2,所以长度为3时还是2
            return 2
        for j in range(4,length+1):
            max = 0
            for i in range(1,j):
                # 思路:每次求解值时将其他小于需要求解的长度是都列出来放在一个数组里
                #如:求长度为5,最优解数组里必须得有长度为1,2,3,4的最优解值
                #注:此处使用列表保存最优解数组是为了性能优化,虽然递归求解也能解出,但会造成大量重复执行
                temp=li[i]*li[j-i]
                if temp>max:
                    max=temp
            li.append(max)#每次将上次所得最优解追加在列表里
        return li[-1]
    
    
    print(rope_cut(8))
  • 相关阅读:
    World Cup
    Eva's Problem
    Number-guessing Game
    WisKey的眼神
    Vowel Counting
    The 3n + 1 problem
    超级楼梯
    母牛的故事
    素数回文
    画8
  • 原文地址:https://www.cnblogs.com/xzm123/p/9849272.html
Copyright © 2020-2023  润新知