Climbing Stairs

来源:互联网 发布:山寨网络机顶盒 编辑:程序博客网 时间:2024/06/05 01:02

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.

第一次提交的代码如下,但是发现代码运行超时。

#include<iostream>using namespace std;class Solution {public:    int climbStairs(int n) {               if(n == 1)            return 1;         else if(n == 2)             return 2;         else             return climbStairs(n-1) + climbStairs(n-2);      } };

然后就想把中间的运算结果保存起来,利用空间换时间的方式提高程序的运行效率,代码如下:

#include<iostream>#include<vector>using namespace std;class Solution {    public:    int climbStairs(int n) {        int* p = new int[n+1];        p[1] = 1;        p[2] = 2;        for(int i = 3; i <= n; i++)        {            p[i] = p[i-1] + p[i-2];        }        return p[n];    }};

但是后来发现原来这个问题可以通过线性代数中的矩阵来解决。

参考链接
Thoughts of Algorithms

Climbing Stairs

原创粉丝点击