1269. 停在原地的方案数
有一个长度为 arrLen 的数组,开始有一个指针在索引 0 处。
每一步操作中,你可以将指针向左或向右移动 1 步,或者停在原地(指针不能被移动到数组范围外)。
给你两个整数 steps 和 arrLen ,请你计算并返回:在恰好执行 steps 次操作以后,指针仍然指向索引 0 处的方案数。
由于答案可能会很大,请返回方案数 模 10^9 + 7 后的结果。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/number-of-ways-to-stay-in-the-same-place-after-some-steps
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
class Solution {
private static final int MOD = 1000000007;
public int numWays(int steps, int arrLen) {
int n = Math.min(arrLen - 1, steps);
int[] dp = new int[n + 1];
dp[0] = 1;
for (int i = 1; i <= steps; i++) {
int[] next = new int[n + 1];
for (int j = 0; j <= n; j++) {
next[j] = dp[j];
if (j - 1 >= 0) {
next[j] = (next[j] + dp[j - 1]) % MOD;
}
if (j + 1 <= n) {
next[j] = (next[j] + dp[j + 1]) % MOD;
}
}
dp = next;
}
return dp[0];
}
}
心之所向,素履以往 生如逆旅,一苇以航

浙公网安备 33010602011771号