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];
}
相关推荐
IvanCodes2 小时前
模型如何自我改进?拆解 RSI 的模型权重与 Harness 两条路线
人工智能·算法·ai·论文·agent·rsi
罗西的思考2 小时前
【轻量化复刻大模型 / KIMI K3】MXFP4 / MXFP8 量化感知训练(QAT)& 演示
人工智能·算法·机器学习
2601_966492314 小时前
C语言变量揭秘
c语言·变量·编译器·线程安全·内存布局
旖旎夜光6 小时前
LeetCode 493: 翻转对 (归并排序) —— 题解
c++·笔记·学习·算法·leetcode·排序算法
阿enna6 小时前
检测指标入门:IoU、Precision、Recall与mAP
人工智能·深度学习·算法·yolo·目标检测·计算机视觉·cnn
Regulus-Moon6 小时前
Quorum:用一个不等式换掉分布式锁
数据结构·论文阅读·分布式·算法·系统架构
专注仿真7 小时前
仿真智能体训练:强化学习多目标奖励算法与实战
python·算法·强化学习·afsim智能体
AndreaYYmm7 小时前
SIGUSR2 触发热重载:一个正在抓包的进程如何原子地换掉规则集
c语言·网络协议
2601_966494728 小时前
C语言是什么
c语言·rust·linux内核·内存管理·系统编程
老师我太想进步了20268 小时前
【数据结构-16】链式二叉树在线OJ题
c语言·数据结构·算法