剑指Offer面试题9 & Leetcode70
Climbing Stairs 斐波那契数列
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?
解题思路
考虑:爬楼梯的方法数相当于斐波那契数列求序号n处数列值。可以使用动态规划,写出递推关系式f(n)=f(n-1)+f(n-2),用两个int值保存f(n-1)和f(n-2),注意递推的初始值,即一阶台阶的方法数为1,二阶台阶的方法数为2,循环求出值。
Solution
public int climbStairs(int n) {
if(n==1) return 1;
else if(n==2) return 2;
else{
int num_n_1 = 2;
int num_n_2 = 1;
for(int i=3;i<=n;i++){
int temp = num_n_1 + num_n_2;
num_n_2 = num_n_1;
num_n_1 = temp;
}
return num_n_1;
}
}