[LeetCode] Number of Ways to Reach a Position After Exactly k Steps

2400. Number of Ways to Reach a Position After Exactly k Steps

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.

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.

Two ways are considered different if the order of the steps made is not exactly the same.

Note that the number line includes negative integers.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Solution {
unordered_map<long long, long long> dp[1010];
long long mod = 1e9 + 7;
long long helper(int now, int fin, int k) {
if(k == 0) return now == fin;
if(dp[k].count(now)) return dp[k][now];
long long& res = dp[k][now] = 0;
res = (res + helper(now + 1, fin, k - 1)) % mod;
res = (res + helper(now - 1, fin, k - 1)) % mod;
return res;
}
public:
int numberOfWays(int startPos, int endPos, int k) {
return helper(startPos, endPos, k);
}
};

Author: Song Hayoung
Link: https://songhayoung.github.io/2022/09/04/PS/LeetCode/number-of-ways-to-reach-a-position-after-exactly-k-steps/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.