LeetCode刷题之Climbing Stairs

Problem

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.

My Solution
class Solution {
    public int climbStairs(int n) {
        int g = 1, h = 2;
        int count = n;
        if (n == 1) {
            return 1;
        } else if (n == 2) {
            return 2;
        }
        while (count > 2) {
            h = g + h; // f(3)
            g = h - g; // f(2)
            count--;
        }
        return h;
    }
}
Great Solution
public class Solution {
    public int climbStairs(int n) {
        double sqrt5=Math.sqrt(5);
        double fibn=Math.pow((1+sqrt5)/2,n+1)-Math.pow((1-sqrt5)/2,n+1);
        return (int)(fibn/sqrt5);
    }
}
    原文作者:Gandalf0
    原文地址: https://www.jianshu.com/p/7e6bb5cd7ced
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞