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?

 题意:有n阶楼梯,每次可以走一步或者两步,总共有多少种方法。

思路:动态规划。维护一个一维数组dp[n+1],dp[0]为n=0时的情况,dp[ i ]为到达第i阶台阶总共的方法。例,当n=4时,如下图,很快就可以推出状态转移方程为:dp[i]=dp[i-1]+dp[i-2] (i >=2)。

[Leetcode] climbing stairs 爬楼梯

代码如下:

 1 class Solution {
 2 public:
 3     int climbStairs(int n) 
 4     {
 5         vector<int> dp(n+1,0);
 6         dp[0]=1,dp[1]=1;
 7         for(int i=2;i<n+1;i++)
 8         {
 9             dp[i]=dp[i-1]+dp[i-2];
10         }    
11         return dp[n];
12     }
13 };

 

相关文章:

  • 2022-01-23
  • 2021-11-18
  • 2022-12-23
  • 2021-07-05
  • 2021-05-16
  • 2021-11-06
  • 2021-10-25
猜你喜欢
  • 2021-12-11
  • 2021-09-16
  • 2022-01-29
  • 2022-02-09
  • 2022-12-23
  • 2022-02-12
  • 2022-12-23
相关资源
相似解决方案