-
Notifications
You must be signed in to change notification settings - Fork 229
/
Copy path1643-kth-smallest-instructions.js
89 lines (81 loc) · 1.49 KB
/
1643-kth-smallest-instructions.js
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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
/**
* @param {number[]} destination
* @param {number} k
* @return {string}
*/
const kthSmallestPath = function (destination, k) {
let v = destination[0],
h = destination[1]
const mu = (c, n) => {
let res = ''
for (let i = 0; i < n; i++) {
res += c
}
return res
}
let res = ''
while (h > 0 && v > 0) {
let pre = comb(h + v - 1, v)
if (k <= pre) {
res += 'H'
h -= 1
} else {
res += 'V'
v -= 1
k -= pre
}
}
if (h == 0) res += mu('V', v)
if (v == 0) res += mu('H', h)
return res
}
function product(a, b) {
let prd = a,
i = a
while (i++ < b) {
prd *= i
}
return prd
}
function comb(n, r) {
if (n == r) {
return 1
} else {
r = r < n - r ? n - r : r
return product(r + 1, n) / product(1, n - r)
}
}
// another
/**
* @param {number[]} destination
* @param {number} k
* @return {string}
*/
const kthSmallestPath = function (destination, k) {
const [r, c] = destination;
const ret = [];
let remDown = r;
for (let i = 0; i < r + c; i++) {
const remSteps = r + c - (i + 1);
const com = comb(remSteps, remDown);
if (com >= k) ret.push("H");
else {
remDown -= 1;
k -= com;
ret.push("V");
}
}
return ret.join("");
};
function comb(n, r) {
if (n < r) return 0;
let res = 1;
if (n - r < r) r = n - r;
for (let i = n, j = 1; i >= 1 && j <= r; --i, ++j) {
res = res * i;
}
for (let i = r; i >= 2; --i) {
res = res / i;
}
return res;
}