[LeetCode]Q70. Climbing Stairs-Easy

系列文章目录

Q2. Add Two Numbers-Medium
Q66. Plus One-Easy


问题:

题目

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?

您正在爬楼梯,到达顶部需要n步。
每次您可以爬1或2步,您可以通过几种不同的方式登顶?

Class Solution{
	public int climbStairs(int n){
	}
}

Sample input/output

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

一、思路

At first, I was breaking down each result into several components, like 3: 1+2=3; 4: 1+3+1=5; 5: 1+4+3=8; 6:1+5+6+1=13; 7: 1+6+10+4… and tried to find the rule in each break down of 2s. Although I did find some rules for existing cases, it easily failed the next case, and it was very time consuming. I then simply just compare the final result, and found that it was just a fibonacci! Then the question became much easier: we just need to return specially for n = 0, n = 1, and n = 2, otherwise just constructing a fibonacci array and return the certain element.

一开始我在拆分计算出的几个结果,列出每个不同数量的2和1的组合的可能性,像3: 1+2=3; 4: 1+3+1=5; 5: 1+4+3=8; 6:1+5+6+1=13; 7: 1+6+10+4…但发现,每当自以为找到规律,用该规律计算出的下一个结果经常是错误的。不仅找不到解法,还十分耗时。后来直接比较总数,发现就是一个简单的斐波那契数列! 这样,只要单独讨论n = 0, n = 1, and n = 2,对于其他数字只用建立对应长度的斐波那契数列并返回对应的元素即可,十分简单。

二、解题

1.第一种方法:最简单

代码如下(示例):

public int climbStairs(int n) {
        if(n > 2) {
            int[] arr = new int[n];
            arr[0] = 1;
            arr[1] = 2;
            for (int i = 2; i < n; i++) {
                arr[i] = arr[i - 1] + arr[i - 2];
            }
            return arr[n - 1];
        }
        return n;
    }

2.结果

在这里插入图片描述

3.总结

这个方法虽然简单,但是并不冗长,也算简洁,运行时间也不长,可以接受

三、总结

As soon as we find out this is a fibonacci problem, the solution is very straightforward. The thing is that how we can find out it is a fibonacci. When I was exploring for the rules, I thought the numbers are very familiar, but it still took a long time for me to realize it is a fibonacci. I should be more sensitive with those special number combinations.
只要发现是斐波那契数列,解法直接了当,难点就在于如何发现是斐波那契。当我还在做无用功拆分找规律的时候就觉得数字眼熟,但是很久后才发现是斐波那契,究其原因还是对数字不够敏感。

一个留学菜狗的刷题心得,欢迎评论指正,或者分享更好的解法!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值