原题
https://leetcode-cn.com/problems/number-of-ways-to-stay-in-the-same-place-after-some-steps/

思路
动态规划
明知道是动态规划,却还是没有具体的思路,于是大佬的题解来了
题解
class Solution {
final static int LEN = 1000000007;
public int numWays(int steps, int arrLen) {
int maxCol = Math.min(steps/2+1, arrLen-1);
int[][] res = new int[steps+1][maxCol+1];
res[0][0] = 1;
for (int i = 1; i <= steps; i++) {
for (int j = 0; j <= maxCol; j++) {
if (j == 0) {
// 位于最左边
res[i][j] = (res[i-1][j] + res[i-1][j+1])%LEN;
} else if (j == maxCol) {
// 位于最右边
res[i][j] = (res[i-1][j] + res[i-1][j-1])%LEN;
} else {
// 位于中间
res[i][j] = ((res[i-1][j-1] + res[i-1][j])%LEN + res[i-1][j+1])%LEN;
}
}
}
return res[steps][0];
}
}

本文解析了如何使用动态规划解决LeetCode上关于走步后保持原地的数学问题。通过实例展示了如何构造状态转移方程,并详细介绍了从边界条件到中间状态的计算过程。

被折叠的 条评论
为什么被折叠?



