Python3爬楼梯算法示例

yipeiwu_com6年前Python基础

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

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

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

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

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

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取最后一个值即可

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相关内容感兴趣的读者可查看本站专题:《Python数据结构与算法教程》、《Python加密解密算法与技巧总结》、《Python编码操作技巧总结》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》及《Python入门与进阶经典教程

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

相关文章

python在命令行下使用google翻译(带语音)

说明1. 使用google翻译服务获得翻译和语音;2. 使用mplayer播放获得的声音文件,因此,如果要播放语音,请确保PATH中能够找到mplayer程序,如果没有mplayer,请...

python使用reportlab画图示例(含中文汉字)

准备工作 开发环境:python2.6,reportlab 准备中文字体文件:simsun.ttc 代码: 复制代码 代码如下:#!/usr/bin/env python2.6#codi...

python读取word 中指定位置的表格及表格数据

python读取word 中指定位置的表格及表格数据

1.Word文档如下: 2.代码 # -*- coding: UTF-8 -*- from docx import Document def readSpecTable(filen...

pyqt5 删除layout中的所有widget方法

如下所示: >>> for i in range(self.gridLayout.count()): >>> self.gridLayout.i...

python使用flask与js进行前后台交互的例子

flask与js进行前后台交互代码如下,后台给前端发数据: python部分: # -*- coding: utf-8 -*- from flask import Flask,jso...