Skip to content

Commit 7529ce6

Browse files
authored
Create 2400-number-of-ways-to-reach-a-position-after-exactly-k-steps.js
1 parent 707e4a9 commit 7529ce6

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
/**
2+
* @param {number} startPos
3+
* @param {number} endPos
4+
* @param {number} k
5+
* @return {number}
6+
*/
7+
var numberOfWays = function(startPos, endPos, k) {
8+
const ll = BigInt, mod = ll(1e9 + 7), N = 1005;
9+
10+
let fact, ifact, inv;
11+
const comb_init = () => {
12+
fact = Array(N).fill(0);
13+
ifact = Array(N).fill(0);
14+
inv = Array(N).fill(0);
15+
fact[0] = ifact[0] = inv[1] = 1n;
16+
for (let i = 2; i < N; i++) inv[i] = (mod - mod / ll(i)) * inv[mod % ll(i)] % mod;
17+
for (let i = 1; i < N; i++) {
18+
fact[i] = fact[i - 1] * ll(i) % mod;
19+
ifact[i] = ifact[i - 1] * inv[i] % mod;
20+
}
21+
};
22+
23+
const comb = (n, k) => {
24+
if (n < k || k < 0) return 0;
25+
return fact[n] * ifact[k] % mod * ifact[n - k] % mod;
26+
};
27+
28+
comb_init();
29+
let res = 0n;
30+
for (let i = 0; i <= k; i++) {
31+
let moveRight = i, moveLeft = k - i;
32+
if (startPos + moveRight - moveLeft == endPos) res += comb(k, i);
33+
}
34+
return res;
35+
36+
};

0 commit comments

Comments
 (0)