题目:
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步上楼,那么给定n阶的楼梯,共有多少种上楼梯的方式。
考虑用递归的方式,也就是每次只考虑前n-2步的时候,然后再加上后面的两阶楼梯的上法,有用1步上的或者是用2步上的。
上1阶的种类共有1种,上2阶的种类共有2种,上3阶的种类共有1+2种,上4阶的种类共有2+1+2种。。。以此类推。
public class Solution
{
public static int climbStairs(int n)
{
//考虑用递归,就是有n步的台阶,那么它的种数由前n-2步的种树和最后两部的走法所决定
int[] length = new int[n + 1];
length[1] = 1;
length[2] = 2;
length[3] = 3;
if(n >= 4)
{
for(int i = 4; i <= n; i++)
{
length[i] = length[i - 2] + length[1] + length[2];
}
}
return length[n];
}
}