-
Notifications
You must be signed in to change notification settings - Fork 0
/
NumOfWaysTOReachAPosition.txt
49 lines (43 loc) · 1.61 KB
/
NumOfWaysTOReachAPosition.txt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
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.
#pragma GCC optimize("O3")
class Solution {
public:
const int mod=1e9 + 7;
int modInverse(int a, int b) {
int x0 = 1, x1 = 0;
int r0 = a, r1 = b;
while (r1 != 0) {
int q = r0/r1, rr = r1, xx = x1;
r1 = r0-q * r1;
x1 = x0-q * x1;
r0 = rr;
x0 = xx;
}
if (x0 < 0) x0+= b;
return x0;
}
int numberOfWays(int s, int e, int k) {
int diff = s - e;
if (k < abs(diff) || (k - diff) & 1) return 0;
if (k==abs(diff)) return 1;
int c = (diff >= 0) ? (k - diff) >> 1 : (k + diff) >> 1;
vector<int> inverse(c+1, 0);
inverse[1] = 1;
#pragma unroll
for (int i = 2; i <= c; i++) {
inverse[i] = modInverse(i, mod);
}
long long ans = 1LL;
#pragma unroll
for (int i = 1; i <= c; i++) {
ans = (ans*(k - i + 1) % mod) * inverse[i] % mod;
}
return ans;
}
};