|
| 1 | +/** |
| 2 | + * 2400. Number of Ways to Reach a Position After Exactly k Steps |
| 3 | + * https://leetcode.com/problems/number-of-ways-to-reach-a-position-after-exactly-k-steps/ |
| 4 | + * Difficulty: Medium |
| 5 | + * |
| 6 | + * You are given two positive integers startPos and endPos. Initially, you are standing at |
| 7 | + * position startPos on an infinite number line. With one step, you can move either one position |
| 8 | + * to the left, or one position to the right. |
| 9 | + * |
| 10 | + * Given a positive integer k, return the number of different ways to reach the position endPos |
| 11 | + * starting from startPos, such that you perform exactly k steps. Since the answer may be very |
| 12 | + * large, return it modulo 109 + 7. |
| 13 | + * |
| 14 | + * Two ways are considered different if the order of the steps made is not exactly the same. |
| 15 | + * |
| 16 | + * Note that the number line includes negative integers. |
| 17 | + */ |
| 18 | + |
| 19 | +/** |
| 20 | + * @param {number} startPos |
| 21 | + * @param {number} endPos |
| 22 | + * @param {number} k |
| 23 | + * @return {number} |
| 24 | + */ |
| 25 | +var numberOfWays = function(startPos, endPos, k) { |
| 26 | + const MOD = 1e9 + 7; |
| 27 | + const dp = new Array(3000).fill().map(() => new Array(k + 1).fill(-1)); |
| 28 | + |
| 29 | + return helper(startPos, endPos, k); |
| 30 | + |
| 31 | + function helper(currentPos, targetPos, remainingSteps) { |
| 32 | + if (currentPos === targetPos && remainingSteps === 0) { |
| 33 | + return 1; |
| 34 | + } |
| 35 | + if (remainingSteps === 0) { |
| 36 | + return 0; |
| 37 | + } |
| 38 | + |
| 39 | + const dpIndex = currentPos + 1000; |
| 40 | + if (dp[dpIndex][remainingSteps] !== -1) { |
| 41 | + return dp[dpIndex][remainingSteps]; |
| 42 | + } |
| 43 | + const leftMove = helper(currentPos - 1, targetPos, remainingSteps - 1); |
| 44 | + const rightMove = helper(currentPos + 1, targetPos, remainingSteps - 1); |
| 45 | + |
| 46 | + dp[dpIndex][remainingSteps] = (leftMove + rightMove) % MOD; |
| 47 | + return dp[dpIndex][remainingSteps]; |
| 48 | + } |
| 49 | +}; |
0 commit comments