|
| 1 | +# 2400. Number of Ways to Reach a Position After Exactly k Steps |
| 2 | + |
| 3 | +- Difficulty: Medium. |
| 4 | +- Related Topics: Math, Dynamic Programming, Combinatorics. |
| 5 | +- Similar Questions: Unique Paths, Climbing Stairs, Reach a Number, Reaching Points, Number of Ways to Stay in the Same Place After Some Steps. |
| 6 | + |
| 7 | +## Problem |
| 8 | + |
| 9 | +You are given two **positive** integers `startPos` and `endPos`. Initially, you are standing at position `startPos` on an **infinite** number line. With one step, you can move either one position to the left, or one position to the right. |
| 10 | + |
| 11 | +Given a positive integer `k`, return **the number of **different** ways to reach the position **`endPos`** starting from **`startPos`**, such that you perform **exactly** **`k`** steps**. Since the answer may be very large, return it **modulo** `109 + 7`. |
| 12 | + |
| 13 | +Two ways are considered different if the order of the steps made is not exactly the same. |
| 14 | + |
| 15 | +**Note** that the number line includes negative integers. |
| 16 | + |
| 17 | + |
| 18 | +Example 1: |
| 19 | + |
| 20 | +``` |
| 21 | +Input: startPos = 1, endPos = 2, k = 3 |
| 22 | +Output: 3 |
| 23 | +Explanation: We can reach position 2 from 1 in exactly 3 steps in three ways: |
| 24 | +- 1 -> 2 -> 3 -> 2. |
| 25 | +- 1 -> 2 -> 1 -> 2. |
| 26 | +- 1 -> 0 -> 1 -> 2. |
| 27 | +It can be proven that no other way is possible, so we return 3. |
| 28 | +``` |
| 29 | + |
| 30 | +Example 2: |
| 31 | + |
| 32 | +``` |
| 33 | +Input: startPos = 2, endPos = 5, k = 10 |
| 34 | +Output: 0 |
| 35 | +Explanation: It is impossible to reach position 5 from position 2 in exactly 10 steps. |
| 36 | +``` |
| 37 | + |
| 38 | + |
| 39 | +**Constraints:** |
| 40 | + |
| 41 | + |
| 42 | + |
| 43 | +- `1 <= startPos, endPos, k <= 1000` |
| 44 | + |
| 45 | + |
| 46 | + |
| 47 | +## Solution |
| 48 | + |
| 49 | +```javascript |
| 50 | +/** |
| 51 | + * @param {number} startPos |
| 52 | + * @param {number} endPos |
| 53 | + * @param {number} k |
| 54 | + * @return {number} |
| 55 | + */ |
| 56 | +var numberOfWays = function(startPos, endPos, k, dp = {}) { |
| 57 | + if (startPos === endPos && k === 0) return 1; |
| 58 | + if (k === 0) return 0; |
| 59 | + if (Math.abs(startPos - endPos) > k) return 0; |
| 60 | + if (!dp[startPos]) dp[startPos] = {}; |
| 61 | + if (dp[startPos][k] === undefined) { |
| 62 | + dp[startPos][k] = ( |
| 63 | + numberOfWays(startPos + 1, endPos, k - 1, dp) + |
| 64 | + numberOfWays(startPos - 1, endPos, k - 1, dp) |
| 65 | + ) % (Math.pow(10, 9) + 7); |
| 66 | + } |
| 67 | + return dp[startPos][k]; |
| 68 | +}; |
| 69 | +``` |
| 70 | + |
| 71 | +**Explain:** |
| 72 | + |
| 73 | +nope. |
| 74 | + |
| 75 | +**Complexity:** |
| 76 | + |
| 77 | +* Time complexity : O(k ^ 2). |
| 78 | +* Space complexity : O(k ^ 2). |
0 commit comments