1269. 停在原地的方案数

链接:

​​​​​​1269. 停在原地的方案数

题解:坐标型动态规划

class Solution {
public:
    int numWays(int steps, int arrLen) {
        if (arrLen <= 0) {
            return 0;
        }
        // 因为需要返回到0下标位置所以,最远也就是一半
        int len = std::min(steps/2+1, arrLen);
        // 走了多少步,到达当前下标dp[step][j],有多少种
        std::vector<std::vector<int>> dp(steps+1, std::vector<int>(len, 0));
        // 从上一步得来,
        std::vector<std::vector<int>> direction{{-1, 0}, {-1, -1}, {-1, 1}};
        dp[0][0] = 1;
        int MOD = 1000000007;
        for (int i = 1; i <= steps; ++i) {
            for (int j = 0; j < len; ++j) {
                for (auto& direc : direction) {
                    int prev_row = i + direc[0];
                    int prev_col = j + direc[1];
                    if (prev_row < 0 || prev_col < 0 || prev_col >= len) {
                        continue;
                    }
                    dp[i][j] = (dp[i][j] + dp[prev_row][prev_col]) % MOD;
                }
            }
        }
        return dp[steps][0];
    }
};
class Solution {
public:
    int numWays(int steps, int arrLen) {
        if (arrLen <= 1) {
            return 1;
        }
        int MOD = 1000000007;
        int len = std::min(steps/2+1, arrLen);
        std::vector<std::vector<int>> dp(steps+1, std::vector<int>(len, 0));
        dp[0][0] = 1;
        for (int step = 1; step <= steps; ++step) {
            dp[step][0] = (dp[step-1][0] + dp[step-1][1])%MOD;
            dp[step][len-1] = (dp[step-1][len-1] + dp[step-1][len-2])%MOD;
            for (int i = 1; i < len-1; ++i) {
                dp[step][i] = ((dp[step-1][i-1] + dp[step-1][i])%MOD + dp[step-1][i+1])%MOD;
            }
        }
        return dp[steps][0];
    }
};

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值