Loading

Leetcode 1269. 停在原地的方案数(简单DP)

有一个长度为 arrLen 的数组,开始有一个指针在索引 0 处。

每一步操作中,你可以将指针向左或向右移动 1 步,或者停在原地(指针不能被移动到数组范围外)。

给你两个整数 steps 和 arrLen ,请你计算并返回:在恰好执行 steps 次操作以后,指针仍然指向索引 0 处的方案数。

由于答案可能会很大,请返回方案数 模 10^9 + 7 后的结果。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/number-of-ways-to-stay-in-the-same-place-after-some-steps
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

一开始想成了杨辉三角组合数啥的,后来发现数组是定长。。。再后来发现最远也就能走step步。。。此题就变成了sb题

class Solution {
public:
    int dp[505][1005];
    const int mod = 1e9 + 7;
    int numWays(int steps, int arrLen) {
        int pos = min(arrLen - 1, steps);
        dp[0][0] = 1;
        for(int i = 1; i <= steps; i++) {
            for(int j = 0; j <= pos; j++) {
                if(j == 0) dp[i][j] = (dp[i - 1][j] + dp[i - 1][j + 1]) % mod;
                else if(j == pos) dp[i][j] = (dp[i - 1][j] + dp[i - 1][j - 1]) % mod;
                else dp[i][j] = ((dp[i - 1][j] + dp[i - 1][j - 1]) % mod + dp[i - 1][j + 1]) % mod;
            }
        }
	    return dp[steps][0];
    }
};
posted @ 2021-05-13 11:24  脂环  阅读(45)  评论(0编辑  收藏  举报