【leedcode】70. Climbing Stairs

来源:互联网 发布:服装设计要学什么软件 编辑:程序博客网 时间:2024/06/06 05:49
题目:

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?

分析:

由提议,设f(n)是上n阶台阶可以走的方式综合。那么f(n) = f(n-1)+f(n-2)。即可以从n-1处走一阶上去,也可以从n-2一次走两阶上去。很明显这是一个斐波那契数列。那么问题就在于如何让计算的复杂度不那么高。我的方法是将之前算出来的结果用数组保存,即如果需要某一处的结果,先访问数组看是否已经有结果,若没有再进行计算。

代码:

#include <iostream>
#include <vector>
using namespace std;
int value(int n, vector<int> &f) {
if (f[n] != 0) {
return f[n];
}
else {
f[n - 1] = value(n - 1, f);
f[n - 2] = value(n - 2, f);
return f[n-1] + f[n-2];
}
}
class Solution {
public:
int climbStairs(int n) {
int a = 0;
vector<int> f;
for (int i = 0; i <= n; i++) {
f.push_back(a);
}
f[0] = 1;
f[1] = 1;
return value(n,f);
}
};


0 0
原创粉丝点击