LeetCode 70. 爬楼梯

70. Climbing Stairs

You are climbing a staircase. It takes n steps to reach the top.

Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?

Example 1:

Input: n = 2

Output: 2

Explanation: There are two ways to climb to the top.

  1. 1 step + 1 step
  2. 2 steps

Example 2:

Input: n = 3

Output: 3

Explanation: There are three ways to climb to the top.

  1. 1 step + 1 step + 1 step
  2. 1 step + 2 steps
  3. 2 steps + 1 step

Constraints:

  • 1 <= n <= 45

解法思路:

// 懵逼的时候:

// 暴力?基本情况?

// 找 最近 重复子问题

// if else

// for while, recursion

// 1: 1

// 2: 2

// 3: f(1) + f(2) 第三个台阶必须从第二个台阶跨一步上去 或者 从第一个台阶跨两步上去

// 4: f(2) + f(3)

// f(n) = f(n-1) + f(n-2) : Fibonacii

class Solution {
    public int climbStairs(int n) {
        // recursion (超时)
        // if (n <= 2) return n;
        // return climbStairs(n-1) + climbStairs(n-2);

        if (n <= 2) return n;
        int first = 1;
        int second = 2;
        int res = 0;
        for (int i = 3; i <= n; i++) {
            res = first + second;
            first = second;
            second = res;
        }
        return res;
    }
}

相关推荐

  1. LeetCode 70. 楼梯

    2023-12-17 02:32:01       46 阅读
  2. Leetcode 70 楼梯

    2023-12-17 02:32:01       39 阅读
  3. LeetCode70 楼梯

    2023-12-17 02:32:01       23 阅读
  4. LeetCode 70 楼梯

    2023-12-17 02:32:01       20 阅读
  5. leetcode70. 楼梯

    2023-12-17 02:32:01       13 阅读

最近更新

  1. TCP协议是安全的吗?

    2023-12-17 02:32:01       16 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2023-12-17 02:32:01       16 阅读
  3. 【Python教程】压缩PDF文件大小

    2023-12-17 02:32:01       15 阅读
  4. 通过文章id递归查询所有评论(xml)

    2023-12-17 02:32:01       18 阅读

热门阅读

  1. MySQL_12.Innodb存储引擎参数

    2023-12-17 02:32:01       33 阅读
  2. 掌握 Go 的计时器

    2023-12-17 02:32:01       43 阅读
  3. Cmake基础(2)

    2023-12-17 02:32:01       31 阅读
  4. 网格布局 Grid

    2023-12-17 02:32:01       42 阅读
  5. ES的字段更改字段类型

    2023-12-17 02:32:01       37 阅读
  6. springBoot使用threadPoolTaskExecutor多线程

    2023-12-17 02:32:01       35 阅读
  7. spring 笔记二 spring配置数据源和整合测试功能

    2023-12-17 02:32:01       31 阅读
  8. Springboot Minio最新版大文件下载

    2023-12-17 02:32:01       45 阅读
  9. C 标准库 - <string.h>

    2023-12-17 02:32:01       30 阅读
  10. echarts 柱形图、折线图点击事件

    2023-12-17 02:32:01       34 阅读
  11. Docker笔记:简单部署 nodejs 项目和 golang 项目

    2023-12-17 02:32:01       34 阅读
  12. Python中的名称空间和作用域

    2023-12-17 02:32:01       38 阅读
  13. NLP中的Seq2Seq与attention注意力机制

    2023-12-17 02:32:01       38 阅读
  14. Unity项目里Log系统该怎么设计

    2023-12-17 02:32:01       30 阅读