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);
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 7,424评论 0 10
  • The Inner Game of Tennis W Timothy Gallwey Jonathan Cape ...
    网事_79a3阅读 12,226评论 3 20
  • 如果 时间能定格 回忆会重播 最好回到两天 一是回家那天 一是离家那天 一个饭最好吃 一个钱最够花 一是初遇那天 ...
    近我者富阅读 338评论 4 6
  • 决赛成绩 光电四轮组 排名学校名称队伍名称成绩 1南昌大学永不疯车21.121 2东华大学缺个队名21.289 3...
    TsinghuaJoking阅读 164评论 0 0
  • 陋习久久祸害,迟迟不改,其根源在内心并不是完全的接受认同。 我总是办事拖拉,事情总要拖到最后一刻才...
    七个十一阅读 141评论 1 0