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.
爬樓梯,非常經(jīng)典的一道題。題意是每次你可以邁一個(gè)或兩個(gè)臺(tái)階,那么爬到第n個(gè)臺(tái)階一共有多少種方法?
由題意可知有兩種方法可以爬到第n個(gè)臺(tái)階,即從第n-1個(gè)臺(tái)階邁一階或從第n-2個(gè)臺(tái)階邁兩階,如果我們用f(i)表示爬到第i階的方法數(shù),則f(n) = f(n-1) + f(n-2)。對(duì)于第1階和第2階,很容易知道f(1) = 1、f(2) = 2,我們把f(n)換成數(shù)組來(lái)表達(dá),就可以解決這道題了。注意先判斷n的值是否小于等于1,否則初始化數(shù)組dp[2]的值時(shí)會(huì)越界。
public int climbStairs(int n) {
if (n < 0) {
return -1;
}
if (n <= 1) {
return 1;
}
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];
}