当前位置:网站首页>February 13, 2022-2-climbing stairs

February 13, 2022-2-climbing stairs

2022-07-06 10:36:00 Procedural ape does not lose hair 2

Suppose you're climbing the stairs . need n You can reach the top of the building .

Every time you climb 1 or 2 A stair . How many different ways can you climb to the top of the building ?

Example 1:

Input :n = 2
Output :2
explain : There are two ways to climb to the top .

  1. 1 rank + 1 rank
  2. 2 rank
    Example 2:

Input :n = 3
Output :3
explain : There are three ways to climb to the top .

  1. 1 rank + 1 rank + 1 rank
  2. 1 rank + 2 rank
  3. 2 rank + 1 rank

Tips :

1 <= n <= 45

java Code :

class Solution {
    public int climbStairs(int n) {
        if(n ==1 || n ==2) {
            return n;
        }

		// Dynamic programming 
        int[] dp = new int[n+1];
        dp[0] =1;
        dp[1] = 1;

        for(int i=2;i<=n;i++) {
            dp[i] = dp[i-1] + dp[i-2];
        }

        return dp[n];
    }
}
原网站

版权声明
本文为[Procedural ape does not lose hair 2]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202131709030359.html