为有牺牲多壮志,敢教日月换新天。

[Swift]LeetCode1269. 停在原地的方案数 | Number of Ways to Stay in the Same Place After Some Steps

★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公众号:山青咏芝(let_us_code)
➤博主域名:https://www.zengqiang.org
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址:https://www.cnblogs.com/strengthen/p/11922002.html
➤如果链接不是山青咏芝的博客园地址,则可能是爬取作者的文章。
➤原文已修改更新!强烈建议点击原文地址阅读!支持作者!支持原创!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★

热烈欢迎,请直接点击!!!

进入博主App Store主页,下载使用各个作品!!!

注:博主将坚持每月上线一个新app!!!

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 still at index 0 after exactly steps steps.

Since the answer may be too large, return it modulo 10^9 + 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 <= arrLen <= 10^6


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

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

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

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

示例 1:

输入:steps = 3, arrLen = 2
输出:4
解释:3 步后,总共有 4 种不同的方法可以停在索引 0 处。
向右,向左,不动
不动,向右,向左
向右,不动,向左
不动,不动,不动
示例  2:

输入:steps = 2, arrLen = 4
输出:2
解释:2 步后,总共有 2 种不同的方法可以停在索引 0 处。
向右,向左
不动,不动
示例 3:

输入:steps = 4, arrLen = 2
输出:8

提示:

1 <= steps <= 500
1 <= arrLen <= 10^6


Runtime: 408 ms
Memory Usage: 38.9 MB
 1 class Solution {
 2     func numWays(_ steps: Int, _ arrLen: Int) -> Int {
 3         let mod:Int = 1000000007
 4         var arr:[Int] = [Int](repeating: 0, count: arrLen)
 5         if arrLen <= 1 {return arrLen}
 6         arr[0] = 1
 7         arr[1] = 1
 8         for j in 1..<steps
 9         {
10             var temp:[Int] = [Int](repeating: 0, count: arrLen)
11             for i in 0...(min(arrLen - 1, steps - j))
12             {
13                 var ans:Int = arr[i]
14                 if i > 0
15                 {
16                     ans = (ans + arr[i - 1]) % mod
17                 }
18                 if i < arrLen - 1
19                 {
20                     ans = (ans + arr[i + 1]) % mod
21                 }
22                 temp[i] = ans
23             }
24             arr = temp
25         }
26         return arr[0]
27     }
28 }

 

posted @ 2019-11-24 12:49  为敢技术  阅读(433)  评论(0编辑  收藏  举报