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?
刚开始看到题目简单的写了个递归,提交超时。后来又仔细推演,发现这不就是斐波那契数列么,于是简单的写个循环提交AC
Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?
刚开始看到题目简单的写了个递归,提交超时。后来又仔细推演,发现这不就是斐波那契数列么,于是简单的写个循环提交AC
int climbStairs(int n)
{
//if (n < 1) return 0;
//else if (n == 1) return 1;
//else if (n == 2) return 2;
//else return climbStairs(n-1) + climbStairs(n-2);
int first = 0, second = 1;
int fib = first + second;
for (int i = 2; i <= n; i++)
{
first = second;
second = fib;
fib = first + second;
}
return fib;
}