脚本之家,脚本语言编程技术及教程分享平台!
分类导航

Python|VBS|Ruby|Lua|perl|VBA|Golang|PowerShell|Erlang|autoit|Dos|bat|

服务器之家 - 脚本之家 - Python - Python3爬楼梯算法示例

Python3爬楼梯算法示例

2021-06-04 00:29zhenghaitian Python

这篇文章主要介绍了Python3爬楼梯算法,涉及Python基于面向对象的字符串遍历、切片、运算等相关操作技巧,需要的朋友可以参考下

本文实例讲述了Python3爬楼梯算法。分享给大家供大家参考,具体如下:

假设你正在爬楼梯。需要 n 步你才能到达楼顶。

每次你可以爬 1 或 2 个台阶。你有多少种不同的方法可以爬到楼顶呢?

注意:给定 n 是一个正整数。

方案一:每一步都是前两步和前一步的和

?
1
2
3
4
5
6
7
8
9
10
11
12
13
class Solution(object):
  def climbStairs(self, n):
    """
    :type n: int
    :rtype: int
    """
    pre, cur = 1, 1
    for i in range(1,n):
      pre,cur = cur,pre+cur
    return cur
#测试
tmp = Solution()
print(tmp.climbStairs(10))

运行结果:

89

方案二:用列表记录每个n对应的值,最后的n取最后一个值即可

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Solution(object):
  def climbStairs(self, n):
    """
    :type n: int
    :rtype: int
    """
    if n == 1:
      return 1
    if n == 2:
      return 2
    res = [1, 2]
    for i in range(2, n):
      res.append(res[i - 1] + res[i - 2])
    return res[-1]
#测试
tmp = Solution()
print(tmp.climbStairs(10))

运行结果:

89

希望本文所述对大家Python程序设计有所帮助。

原文链接:https://blog.csdn.net/zhenghaitian/article/details/81074773

延伸 · 阅读

精彩推荐