解法:
dp[i]:到第i阶梯,总共dp[i]种方案
状态转移方程:
base condition:
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
#define endl '\n'
int main() {vector<long long> dp(51,0);dp[1] = 1;dp[2] = 2;dp[3] = 4;for (int i = 4; i < 51; i++) {dp[i] = dp[i - 1] + dp[i - 2] + dp[i - 3];}int t, n;cin >> t;while (t--) {cin >> n;cout << dp[n] << endl;}return 0;
}
拓展:
若每次最多上m阶
dp[i]:到第i阶梯,总攻dp[i]种方案
状态转移方程:
base condition:
...
直到,但是显然dp[2]=dp[1]+dp[0]=2。所以还需要dp[0]=1
m等于1时,显然dp[1]=dp[0]=1
所以最终只需要初始化dp[0]=1。
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
#define endl '\n'
int main() {int n, m;cin >> n >> m;vector<long long> dp(n + 1, 0);dp[0] = 1;for (int i = 1; i <= n; i++) {for (int j = 1; j <= m; j++) {if (i - j >= 0) dp[i] += dp[i - j];}cout << dp[i] << endl;}return 0;
}