在线时间:8:00-16:00
迪恩网络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 Input: steps = 2, arrLen = 4 Input: steps = 4, arrLen = 2 Constraints: 1 <= steps <= 500 有一个长度为 arrLen 的数组,开始有一个指针在索引 0 处。 每一步操作中,你可以将指针向左或向右移动 1 步,或者停在原地(指针不能被移动到数组范围外)。 给你两个整数 steps 和 arrLen ,请你计算并返回:在恰好执行 steps 次操作以后,指针仍然指向索引 0 处的方案数。 由于答案可能会很大,请返回方案数 模 10^9 + 7 后的结果。 示例 1: 输入:steps = 3, arrLen = 2 输入:steps = 2, arrLen = 4 输入:steps = 4, arrLen = 2 提示: 1 <= steps <= 500 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 }
|
请发表评论