问题描述
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?
Note: Given n will be a positive integer.
Example 1:
Input: 2
Output: 2
Explanation: There are two ways to climb to the top.
1. 1 step + 1 step
2. 2 steps
Example 2:
Input: 3
Output: 3
Explanation: There are three ways to climb to the top.
1. 1 step + 1 step + 1 step
2. 1 step + 2 steps
3. 2 steps + 1 step
中文题意
爬n阶的楼梯,每次只能爬1阶或者2阶,求有几种爬阶方式。
方法一
(1)如果n=1,那么只能一次一阶,有一种方式;
(2)如果n=2,那么可以一次一阶,两次到达顶端;或者是一次2阶,共两种方式;
(3)在其他情况中,Step(i)表示到第i阶的方法总数,那么i,i-1,i-2之间的关系为:Step(i)=Step(i-1)+Step(i-2)。(自底向上和自上向下都满足)。
class Solution {
public int climbStairs(int n) {
if(n <= 2){
return n;
}
int num1 = 1;
int num2 = 2;
int num = 0;
for(int i = 3; i <n+1;i++){
num = num1 + num2;
num1 = num2;
num2 = num;
}
return num;
}
}
方法二
使用数学中的排列组合
总阶数为n,那么一次2阶出现的最多情况为i=n/2。那么一次1阶出现的总数为n-2i,总的步数为i+n-2i=n-i。使用组合的概念,就相当于从总次数(n-i)中抽取i次的组合数。
class Solution {
public int climbStairs(int n) {
double i = n/2;//i表示一步2阶出现的最高次数
double sum = 1;//记录方法数
for(int l = 1;l < i+1;l++){//某次一步2阶出现l次
double temp = n-l;
for(int k = 1; k < l;k++){//计算组合公式中的分子,即(n-l)*(n-l-1)*...*(n-l-l+1)
temp = temp * (n-l-k);
}
for(int m = l;m > 0;m--){//计算组合公式中的分母,即l*(l-1)*(l-2)*...*1
temp /= m;
}
sum += temp;
}
return (int)sum;
}
}
tips:在方法二中,使用了double类型的变量,是因为for循环中使用有/的运算,如果使用int后,那么偏差会越来越大。