LeetCode //C - 1269. Number of Ways to Stay in the Same Place After Some Steps

1269. Number of Ways to Stay in the Same Place After Some Steps

You have a pointer at index 0 in an array of size arrLen. At each step, you can move 1 position to the left, 1 position to the right in the array, or stay in the same place (The pointer should not be placed outside the array at any time).

Given two integers steps and arrLen, return the number of ways such that your pointer is still at index 0 after exactly steps steps. Since the answer may be too large, return it modulo 10 9 + 7 10^9 + 7 109+7.

Example 1:

Input: steps = 3, arrLen = 2

Output: 4

Explanation: There are 4 differents ways to stay at index 0 after 3 steps.

Right, Left, Stay

Stay, Right, Left

Right, Stay, Left

Stay, Stay, Stay

Example 2:

Input: steps = 2, arrLen = 4

Output: 2

Explanation: There are 2 differents ways to stay at index 0 after 2 steps

Right, Left

Stay, Stay

Example 3:

Input: steps = 4, arrLen = 2

Output: 8

Constraints:
  • 1 <= steps <= 500
  • 1 < = a r r L e n < = 10 6 1 <= arrLen <= 10^6 1<=arrLen<=106

From: LeetCode

Link: 1269. Number of Ways to Stay in the Same Place After Some Steps


Solution:

Ideas:

dpi means ways to be at index i after current steps.

Each step: stay, move from left, or move from right.

Code:
c 复制代码
int numWays(int steps, int arrLen) {
    int MOD = 1000000007;
    int maxPos = steps < arrLen ? steps : arrLen - 1;

    long long dp[501] = {0};
    long long next[501] = {0};

    dp[0] = 1;

    for (int s = 1; s <= steps; s++) {
        for (int i = 0; i <= maxPos; i++) {
            next[i] = dp[i];  // stay

            if (i > 0)
                next[i] = (next[i] + dp[i - 1]) % MOD;  // move right to i

            if (i < maxPos)
                next[i] = (next[i] + dp[i + 1]) % MOD;  // move left to i
        }

        for (int i = 0; i <= maxPos; i++) {
            dp[i] = next[i];
            next[i] = 0;
        }
    }

    return (int)dp[0];
}
相关推荐
文丑颜不良啊30 分钟前
LeetCode51~75题目解析
leetcode
高晶34 分钟前
无乘法器实现LC二阶滤波器:基于移位运算的快速算法与四种精度推导
算法·设计模式·程序员
ysbfsy37 分钟前
大数计算思路
算法
高晶1 小时前
主从自动分配算法:平均值乘以设备数一半的选举基准值解析
算法·设计模式·程序员
学电子她就能回来吗1 小时前
LeetCode Hot 100|普通数组专题学习笔记(零基础版)
笔记·算法·leetcode
用户老李1 小时前
反向传播计算梯度举例
算法
niyongsheng1 小时前
多智能体连续时间内路径规划:AA-SIPP(m) 的 Rust 实现与算法
算法·rust·机器人
302wanger2 小时前
DeepSeek-V4.1-Flash-1017 免费用到1024,速来
算法
lisw053 小时前
微分与积分的本质区别解析
算法·数学建模·极限编程
鱼很腾apoc3 小时前
【MySQL】第4期 用户管理与 C 语言连接编程详解
linux·服务器·c语言·mysql·connector/c