题目描述:
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?
我的代码:
public class Solution {
/**
* 求爬楼梯的方式的数量,每次可以爬一阶或两阶
* @param n 楼梯高度
* @return 返回爬楼梯的方式的数量
*/
public int climbStairs(int n) {
if(n==1 || n== 2)
return n;
int[] dp = new int[n+1];
dp[1] = 1;
dp[2] = 2;
//采用动态规范的方式
for(int i = 3;i<=n;i++)
dp[i] = dp[i-1] + dp[i-2];
return dp[n];
}
}
解析:
因为每次只能爬一阶或者两阶,所以呢,爬一阶的时候只有一种爬法,但是爬两阶的时候又两种爬法,一种是一次爬两阶,一种是爬两次,每次爬一阶。所以,大问题是爬n阶有几种爬法,其实只有两种,一种是爬到n-1层的方法总数,然后1步爬到n层,另一种是爬到n-2层的方法总数,然后2步爬到n层。