問題描述
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後,那麼偏差會越來越大。