美文网首页
1 - Easy - 爬楼梯

1 - Easy - 爬楼梯

作者: 1f872d1e3817 | 来源:发表于2018-07-22 15:47 被阅读0次

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

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

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

示例 1:

输入: 2
输出: 2
解释: 有两种方法可以爬到楼顶。

  1. 1 步 + 1 步
  2. 2 步
    示例 2:

输入: 3
输出: 3
解释: 有三种方法可以爬到楼顶。

  1. 1 步 + 1 步 + 1 步
  2. 1 步 + 2 步
  3. 2 步 + 1 步

实际上是斐波那契数列

class Solution(object):
    def climbStairs(self, n):
        steps = [1, 2]
        for i in range(3, n+1):
            steps.append(steps[-1] + steps[-2])
        return steps[n-1]

下面的方法可以计算出所有的走法,但是超时

class Solution(object):
    def climbStairs(self, n):
        """
        :type n: int
        :rtype: int
        """
        steps = [["1"], 
                 ["11", "2"]]
        if n < 3:
            return len(steps[n-1])
        for i in range(3, n+1):
            last = steps[-1]
            temp = []
            for s in last:
                _left = "1" + s
                if _left not in temp:
                    temp.append(_left)
                _right = s + "1"
                if _right not in temp:
                    temp.append(_right)
            lastlast = steps[-2]
            for s in lastlast:
                _left = "2" + s
                if _left not in temp:
                    temp.append(_left)
                _right = s + "2"
                if _right not in temp:
                    temp.append(_right)
            steps.append(temp)
        return len(steps[n-1])

相关文章

  • 1 - Easy - 爬楼梯

    假设你正在爬楼梯。需要 n 步你才能到达楼顶。 每次你可以爬 1 或 2 个台阶。你有多少种不同的方法可以爬到楼顶...

  • LeetCode | 0070. Climbing Stairs

    LeetCode 0070. Climbing Stairs爬楼梯【Easy】【Python】【动态规划】 Pro...

  • 70. 爬楼梯(easy)

    假设你正在爬楼梯。需要 n 阶你才能到达楼顶。每次你可以爬 1 或 2 个台阶。你有多少种不同的方法可以爬到楼顶呢...

  • 70. 爬楼梯

    [toc] leetcode 难度:easy 题目 假设你正在爬楼梯。需要 n 阶你才能到达楼顶。 每次你可以爬 ...

  • 每周一道算法题(五十三)

    本周题目难度'Easy',使用语言'Python' 题目:本周的题目就是最简单的动规入门,就是假设你正在爬楼梯。每...

  • 每天一题LeetCode【第51天】

    T70. Climbing Stairs【Easy】 题目 你要爬楼梯。你面对的是一个 n 步可以走上去的楼梯。 ...

  • 2017-11-01

    1.It is easy to learn English,but it is not easy to speak...

  • tag5:动态规划 爬楼梯+打家劫舍

    1、爬楼梯 leetcode70. 爬楼梯[https://leetcode-cn.com/problems/cl...

  • LeetCode 1. Two Sum (Easy)

    LeetCode 1. Two Sum (Easy) LeetCode 1. Two Sum (Easy) 原题链...

  • 腾讯云Ubuntu配置AnkiServer

    1.使用easy_install 安装AnkiServer: $ easy_install AnkiServer ...

网友评论

      本文标题:1 - Easy - 爬楼梯

      本文链接:https://www.haomeiwen.com/subject/pvnlmftx.html