题目:Climbing Stairs
难度:easy
问题描述:
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?
解题思路:爬梯子,每次爬1格或者2格,求有多少种爬法。解题关键:从终点开始算,第I级梯子的爬法=(I-1)级的爬法+(I-2)级的爬法。
使用动态规划即可。第一种方法设置了数组ways[I]来记录每级梯子的爬法。第二种进行了优化,只记录要算的梯子方法数的前两级梯子的爬法。
方法一代码如下:
public static int climbStairs(int n) {
int[] ways=new int[n+1];
if(n==1||n==0){
return 1;
}
ways[n--]=1;
ways[n--]=1;
while(n>=0){
ways[n]=ways[n+1]+ways[n+2];
n--;
}
return ways[0];
}
方法二代码如下:
public static int climbStairs2(int n) {
int qian,hou,temp;
if(n==1||n==0){
return 1;
}
qian=1;//上一级
hou=1;
n=n-2;
while(n>=0){
temp=qian+hou;
qian=hou;
hou=temp;
n--;
}
return hou;
}