LeetCode三步问题(动态规划)
- 编写代码
- 代码优化
链接: 三步问题
编写代码
class Solution {
public:
int waysToStep(int n) {
if(n == 1 || n == 2) return n;
vector<int> dp(n+1);
const int MOD = 1e9 + 7;
dp[0] = dp[1] = 1;
dp[2] = 2;
for(int i = 3;i<=n;++i)
{
dp[i] = ((dp[i - 1] + dp[i - 2]) % MOD + dp[i - 3]) % MOD;
}
return dp[n];
}
};
代码优化
class Solution {
public:
int waysToStep(int n) {
if(n == 1 || n == 2) return n;
int a = 1,b = 2,c = 4,d = 0;
const int MOD = 1e9 + 7;
for(int i = 4;i<=n;++i)
{
d = ((b + c) % MOD + a) % MOD;
a = b;
b = c;
c = d;
}
return c;
}
};