DP Topic 2 Climbing Stairs |

topic:

Idea:

        According to the meaning of the question, we first find the number of corresponding n-level steps.

        n = 1        f(n) = 1

        n = 2        f(n) = 2

        n = 3        f(n) = 3

        n = 4        f(n) = 5

        n = 5        f(n) = 8

        ......            ......

        n = n        f(n) = f(n - 2) + f(n - 1)

So through the listed examples, we can find the corresponding rules, and then derive the formula:

n = n        f(n) = f(n - 2) + f(n - 1)

Therefore, we can make it clear that the meaning of i in dp[i] is the number of corresponding step plans, and record the corresponding i 

The code is explained in detail below:

#include <iostream>
#include <cstring>
#include <algorithm>
#include <queue>
#include <unordered_map>
#define endl '\n'
#define int long long
#define YES puts("YES")
#define NO puts("NO")
#define umap unordered_map
#define All(x) (x).begin(),(x).end()
#pragma GCC optimize(3,"Ofast","inline")
#define ___G std::ios::sync_with_stdio(false),cin.tie(0), cout.tie(0)
using namespace std;
const int N = 2e6 + 10,MOD = 10007;

int dp[N];	

int f(int x)
{
	// 如果相应台阶方案数计算过了
	// 直接返回之前计算过的结果
	if(dp[x]) return dp[x] % MOD;
	
	return (dp[x] = f(x - 1) % MOD + f(x - 2) % MOD);
}

inline void solve()
{
	// dp 初始化
	dp[1] = 1;
	dp[2] = 2;
	
	int n;

	cin >> n;
	
	cout << f(n) % MOD << endl;
	
}


signed main()
{
//	freopen("a.txt", "r", stdin);
	___G;
	int _t = 1;
//	cin >> _t;
	while (_t--)
	{
		solve();
	}

	return 0;
}

Last commit:

Guess you like

Origin blog.csdn.net/hacker_51/article/details/132874875