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);
}
}