70. Climbing Stairs

浅浅的花香味﹌ 2022-05-16 15:56 192阅读 0赞

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.

Example 1:

  1. Input: 2
  2. Output: 2
  3. Explanation: There are two ways to climb to the top.
  4. 1. 1 step + 1 step
  5. 2. 2 steps

Example 2:

  1. Input: 3
  2. Output: 3
  3. Explanation: There are three ways to climb to the top.
  4. 1. 1 step + 1 step + 1 step
  5. 2. 1 step + 2 steps
  6. 3. 2 steps + 1 step

题意:有n阶楼梯, 每次可以爬1层或2层,总有多少种走法。

方法一:动态规划,状态转移方程是 count[i] = count[i-1] + count[i-2]; count[i]表示i个台阶有多少种走法。

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

发表评论

表情:
评论列表 (有 0 条评论,192人围观)

还没有评论,来说两句吧...

相关阅读