每天一刷,强迫学习
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?
很经典的面试题,斐波那契求解:f(n)=f(n-1)+f(n-2)。最简单的思路就是递归,优化的做法是用动态规划的思想保存已经算出的子问题的解来避免重复计算,提高计算效率。求没什么可多说的。
有一点比较有意思的是长期不做算法忘了如何证明这是一个斐波那契数列了。证明方法:
有n个台阶时,第一步有两种走法:走一步,剩下n-1个台阶有f(n-1)中走法;走两步,剩下n-2个台阶有f(n-2)中走法。
public class Solution {
public int climbStairs(int n) {
int tempFir = 1;
int tempSec = 2;
int temp = 0;
if(n < 0)
return -1;
if(n == 1)
return 1;
if(n == 2)
return 2;
for(int i = 3; i <= n; i++){
temp = tempSec;
tempFir += tempSec;
tempSec = tempFir;
tempFir = temp;
}
return tempSec;
}
}