1. 程式人生 > >leetCode 70.Climbing Stairs (爬樓梯) 解題思路和方法

leetCode 70.Climbing Stairs (爬樓梯) 解題思路和方法

Climbing Stairs 

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?

思路:題目也比較簡單,類似斐波那契。

程式碼如下:

public class Solution {
    public int climbStairs(int n) {
        //此題類似斐波那契數列
        if(n <= 0){
            return 0;
        }
        if(n <= 1){
            return 1;
        }
        if( n <= 2){
            return 2;
        }
        int i = 3;
        int f1 = 1;
        int f2 = 2;
        int f3 = 0;
        while(i++ <= n){
            f3 = f1+f2;
            f1 = f2;
            f2 = f3;
        }
        return f3;
    }
}