问题描述
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?
翻译
你正在爬楼梯,到达顶部需要n步,每次你可以爬1步或2步。你爬到顶部的不同方式有多少种?
思路
初始化 dp[1]、dp[2] 往后求斐波那契数列
代码
#define _CRT_SECURE_NO_WARNINGS 1
#include <iostream>
using namespace std;
const int N = 1e6 + 10;
int dp[N] = { 0 };
int climb(int a[], int n)
{
for (int i = 3; i <= n; i++)
a[i] = a[i-2] + a[i - 1];
return a[n];
}
int main()
{
int n;
cout << "Enter the number of stairs:" << endl;
cin >> n;
dp[1] = 1;//一阶一种
dp[2] = 2;//两阶两种
int a=climb(dp, n);
cout << a;
return 0;
}
测试案例
10
运行结果
89
时间复杂度分析
O(n)
速记
初始化:dp[1] = 1;//一阶一种 dp[2] = 2;//两阶两种
斐波那契