[leetcode][Climbing Stairs]

5月份面试时也被问到相同的问题,第一次使用leetcode,这种OJ的代码机制很有意思啊

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?

最简单但是在大量数据监测时会超时的solution


public class Solution {
    public int climbStairs(int n) {
        // Start typing your Java solution below
        // DO NOT write main() function
        if(n==1) return 1;
        else if(n==2) return 2;
        else return climbStairs(n-1)+climbStairs(n-2);
        
    }
}
该题的讨论界面 http://discuss.leetcode.com/questions/246/climbing-stairs,实际上可以转换成斐波那契数列进行解答



public class Solution {
    public int climbStairs(int n) {
        // Start typing your Java solution below
        // DO NOT write main() 
    double s = Math.sqrt(5);
   return (int)Math.floor(1/s*( Math.pow(0.5+s/2,(double)n+1)-Math.pow(0.5-s/2,(double)  
    }
}
注意很容易返回“
possible loss of precision
”的error

你可能感兴趣的:([leetcode][Climbing Stairs])