70-Climbing Stairs

来源:互联网 发布:协同过滤算法的实现 编辑:程序博客网 时间:2024/05/21 12:46

类别:dynamic programming
难度:easy

题目描述

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?

这里写图片描述

算法分析

动态规划:
当台阶的数目>2的时候,最与最后一步,总是有两种选择,走一步或者是走两步,这两种情况的走法总是不一样,所以可以直接利用前面的结果进行递推,从而得到A[i] = A[i -1] + A[i-2]
这道题目用递归在思路上也没有问题,但是会超时。

代码实现

// dynamic programmingclass Solution {public:    int steps[1000];    int climbStairs(int n) {        steps[0] = 0;        steps[1] = 1;        steps[2] = 2;        //  对于最后一步,总是可以走一步或者是走两步,所以可以直接使用前面的计算结果        //  使用递归会超时,所以将前面的计算结果存储在数组中。        for (int i = 3; i <= n; ++i) {            steps[i] = steps[i - 1] + steps[i - 2];        }        return steps[n];    }};
原创粉丝点击