[week 10][Leetcode][Dynamic Programming] Climbing Stairs

来源:互联网 发布:acfunfix.js 编辑:程序博客网 时间:2024/05/01 21:47
  • Question:

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. 


  • Analysis:

这是一个爬梯子的问题,要到达第n级阶梯则只能是从n-1级阶梯一步跨上来或者是从n-2级阶梯一次跨两步上来,由此很容易可以得到状态转移方程为:

S[n] = S[n-1] + S[n-2]。代码如下所示:

  • Code:
class Solution {public:    int climbStairs(int n) {        int result = 0;        int temp[n+1] = {1};        temp[1] = 1;        for (int i=2;i<=n;i++)        {            temp[i] = temp[i-1] + temp[i-2];        }        return temp[n];    }};


原创粉丝点击