LeetCode 70 _ Climbing Stairs 爬楼梯 (Easy)

Description:

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

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

Note: Given n will be a positive integer.

Example 1:

Input: 2
Output: 2
Explanation: There are two ways to climb to the top.
1. 1 step + 1 step
2. 2 steps

Example 2:

Input: 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

 

 

Solution:

这道题说的是,每次可以走1步或2步,问n步有多少种走法

 

当看到这种后一步的结果和前一步的方法相关的时候,大多就是使用Dynamic Programming方法去解决。

我们随意举个栗子,假设一共需要走8步:

 1  2   3   4   5  6  7   8  

— — — — — — — — 

到达第1格的时候,只能从起点走1步过去,即1种方法;

到达第2格的时候,可从起点走2步过去和从第1格走1步过去,即2种方法;

那么到达第3格的时候呢?可以从第1格走2步,和第2格走一步,走到第1格只有1种方法,因此途径第1格到第3格一共只有1种方法;而走到第2格有2种方法,因此途径第2格到第3格有2种方法;这样相加起来一共3种;

向后继续推断此我们可以发现,其实每一步都和它前面的两步相关,再继续向后尝试,发现它其实就是一个斐波那契数列啦~

 1  2   3   4   5  6  7   8  

— — — — — — — — 

 1  2   3  5   8  .....

 

 

Code:

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

 

 

提交情况:

Runtime: 0 ms, faster than 100.00% of Java online submissions for Climbing Stairs.
Memory Usage: 31.9 MB, less than 100.00% of Java online submissions for Climbing Stairs.

posted @ 2019-04-09 19:18  Doris7  阅读(131)  评论(0编辑  收藏  举报