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階,那有幾種方式可以到達最上面的那一階?
題解:
這題是利用動態規劃來解題,而解法類似於費伯納西數列(費氏數列),所有路徑於下面:
f(0) = 1
f(1) = 1:1
f(2) = 2:1+1,2
f(3) = 3:1+1+1,2+1,1+2
f(4) = 5:1+1+1+1,2+2,1+2+1,1+1+2,2+1+1
f(6) = 8:1+1+1+1+1+1,1+1+1+1+2....
從上面的例子當中可以得出下面的遞歸式:
ways[i] = 0 if i <= 1, i = 0;
ways[i] = ways[i-1] + ways[i-2] if i < 1
從上面的遞歸式可以有下面的解法:
package LeetCode.Easy;
/*
f(0) = 1
f(1) = 1:1
f(2) = 2:1+1,2
f(3) = 3:1+1+1,2+1,1+2
f(4) = 5:1+1+1+1,2+2,1+2+1,1+1+2,2+1+1
f(6) = 8:1+1+1+1+1+1,1+1+1+1+2....
結果類似於費伯納西數列(費氏數列): ways[i] = ways[i-1] + ways[i-2]
*/
public class ClimbingStairs {
public int climbStairs(int n) {
int[] ways = new int[n + 1];
ways[0] = 1; //爬0階只有一種方式
ways[1] = 1;
for(int i = 2; i <= n; i ++) {
ways[i] = ways[i - 1] + ways[i - 2];
}
return ways[n];
}
}