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];
}
相关推荐
秋天的怀念_David24 分钟前
算法一千零一夜 · 第二十八夜 注册
java·程序人生·算法
Rain的Java大神之路2 小时前
LeetCode 37 解数独面试攻略:回溯 + 位掩码 + MRV,从暴力到毫秒级求解
java·后端·leetcode
NEFU_Jyj2 小时前
贝尔数(组合数学)
算法
希和20273 小时前
C语言程序设计题|有序数组插入数字冒泡排序
c语言·数据结构·算法
Pniubi3 小时前
力扣73 矩阵置零
算法·leetcode·矩阵
布莱克60513 小时前
C++ 中 map 的 insert 与 emplace:key 已存在时会覆盖吗?
开发语言·数据结构·c++·算法·map
D e re k ZH16 小时前
C++ 系统学习手记:从语法细节到工程实践
开发语言·数据结构·c++·算法
石小石Orz17 小时前
AI 正在蚕食我们的编码能力
前端·后端·算法
Zwawa18 小时前
屏幕不止一种:OLED、LCD1602字符屏、TFT/IPS图形屏和串口屏怎么用,这与TTY和PTY又有什么关系
c语言·单片机·嵌入式