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)典的一道題裸删。題意是每次你可以邁一個或兩個臺階院喜,那么爬到第n個臺階一共有多少種方法?
由題意可知有兩種方法可以爬到第n個臺階宇智,即從第n-1個臺階邁一階或從第n-2個臺階邁兩階,如果我們用f(i)表示爬到第i階的方法數(shù),則f(n) = f(n-1) + f(n-2)棉饶。對于第1階和第2階表箭,很容易知道f(1) = 1赁咙、f(2) = 2,我們把f(n)換成數(shù)組來表達(dá),就可以解決這道題了彼水。注意先判斷n的值是否小于等于1崔拥,否則初始化數(shù)組dp[2]的值時會越界。
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];
}