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];
}
相关推荐
2601_965742221 小时前
短视频脚本创作方法分享:本地生活类账号的起步思路
大数据·人工智能·算法·ai·新媒体运营·生活
55873生态系统手记1 小时前
读完 55873 资产钱包的技术栈,我重新理解了 "合规钱包" 应该长什么样
算法·架构
旋生万物1 小时前
素数螺旋映射 $z_n=n^{1+i}$ 的角分布统计检验与零模型对比
大数据·前端·人工智能·算法·云原生·螺旋生成论·螺旋相位
HRTOS1 小时前
HRTOS Shell继续完善:优化printf缓冲区与字符串越界保护,国庆后随新版本更新
运维·单片机·嵌入式硬件·算法·51单片机
邵奈一2 小时前
当沉香之乡遇上 Seed-2.1-pro:我用 AI 给村子做了一个数字门面
算法·架构
垆边人似月.2 小时前
华为机考题:矩阵中的最长递增路径
c语言·c++
海天一色y2 小时前
图像分割全解析:从经典算法到深度学习的原理与实战(Python + MATLAB)
python·深度学习·算法
垆边人似月.2 小时前
华为算法题:最长连续递增子序列的变
数据结构·算法·leetcode
YOLO数据集集合2 小时前
机器学习二分类预测算法组合工具:12种算法、113种组合的批量建模方案8031期
算法·机器学习