[leetcode]: 70. Climbing Stairs

来源:互联网 发布:c语言less 编辑:程序博客网 时间:2024/06/05 06:27

1.题目

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.

爬楼梯,一共n级。一次可以爬一级或两级,问有多少种方式。

2. 分析

动态规划问题。也可以看做斐波那契数列。
dp[i]表示i级台阶共多少种方式
dp[i]=dp[i-1]+dp[i-2]

3.代码

class Solution {public:    int climbStairs(int n) {        if(n<1)            return 0;        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];    }};
原创粉丝点击