这道题目第一思路就是递归暴力枚举,不难写出如下C++代码
typedef long long LL;
const int mod = (int)1e9 + 7;
class Solution {
public:
int numWays(int steps, int arrLen) {
dfs(steps, 0, arrLen);
return res % mod;
}
LL res = 0;
void dfs(int steps, int i, int arrLen){
if(steps == 0){
if(i == 0){
res++;
}
return;
}
if(i + 1 < arrLen){
dfs(steps - 1, i + 1, arrLen);
}
if(i - 1 >= 0){
dfs(steps - 1, i - 1, arrLen);
}
dfs(steps - 1, i, arrLen);
}
};
对于题目中的步数,这样的搜索显然是超时的,所以最直接的解法,就是做记忆话优化。最简单优雅的实现是用Python来写
class Solution:
def numWays(self, steps: int, arrLen: int) -> int:
mod_ = 10**9 + 7
@lru_cache(None)
def f(steps, i):
if steps == 0:
return 1 if i == 0 else 0
ans = 0
ans += f(steps - 1, i) % mod_
if i > 0:
ans += f(steps - 1, i - 1) % mod_
if i < arrLen - 1:
ans += f(steps - 1, i + 1) % mod_
return ans % mod_
return f(steps, 0)
改成动态规划实现:
const int MOD = (int)1e9 + 7;
class Solution {
public:
int numWays(int steps, int arrLen) {
// f[i][j]表示第i步走到位置j的方案数
// f[i][j] = f[i-1][j] + f[i-1][j-1] + f[i-1][j+1]
vector<vector<int>> f(steps+1, vector<int>(arrLen));
f[0][0] = 1;
for(int i = 1; i <= steps; i++){
for(int j = 0; j < arrLen; j++){
f[i][j] = f[i - 1][j] % MOD;
if(j >= 1){
f[i][j] = (f[i][j] + f[i - 1][j - 1]) % MOD;
}
if(j < arrLen - 1){
f[i][j] = (f[i][j] + f[i - 1][j + 1]) % MOD;
}
}
}
return f[steps][0];
}
};
还是超时,因为当数组长度比较大,但steps比较小时,存在大量重复计算
因此优化一下状态空间:
const int MOD = (int)1e9 + 7;
class Solution {
public:
int numWays(int steps, int arrLen) {
// f[i][j]表示第i步走到位置j的方案数
// f[i][j] = f[i-1][j] + f[i-1][j-1] + f[i-1][j+1]
int maxLen = min(arrLen, steps);
vector<vector<int>> f(steps + 1, vector<int>(maxLen + 1));
f[0][0] = 1;
for(int i = 1; i <= steps; i++){
for(int j = 0; j < maxLen; j++){
f[i][j] = f[i - 1][j];
if(j >= 1){
f[i][j] = (f[i][j] + f[i - 1][j - 1]) % MOD;
}
if(j < maxLen - 1){
f[i][j] = (f[i][j] + f[i - 1][j + 1]) % MOD;
}
}
}
return f[steps][0];
}
};
后续还可以优化空间。