Skip to content

Commit a742357

Browse files
authored
Create 2152-minimum-number-of-lines-to-cover-points.js
1 parent b2df826 commit a742357

File tree

1 file changed

+58
-0
lines changed

1 file changed

+58
-0
lines changed
Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
/**
2+
* @param {number[][]} points
3+
* @return {number}
4+
*/
5+
const minimumLines = function(points) {
6+
const n = points.length;
7+
const connects = Array.from({ length: n }, () => Array(n).fill(0));
8+
for(let i = 0; i < n; ++i) {
9+
for(let j = i + 1; j < n; ++j) {
10+
connects[i][j] = (1 << i) | (1 << j);
11+
let dx = points[j][0] - points[i][0];
12+
let dy = points[j][1] - points[i][1];
13+
for(let k = j + 1; k < n; ++k) { // check if k will be on the line connecting i and j.
14+
let dx2 = points[k][0] - points[i][0];
15+
let dy2 = points[k][1] - points[i][1];
16+
if (dx * dy2 == dy * dx2) {
17+
connects[i][j] |= (1 << k);
18+
}
19+
}
20+
}
21+
}
22+
const dp = new Array(1<<n).fill(Infinity);
23+
return helper(n, 0, dp, connects);
24+
};
25+
26+
function helper(n, mask, dp, connects) {
27+
if (dp[mask] == Infinity) {
28+
let has = numOfOne(mask);
29+
if (has == n) { // if all the points have been connected
30+
dp[mask] = 0;
31+
} else if (has >= n - 2) { // if only 2 points left
32+
dp[mask] = 1;
33+
} else { // if there are more than 2 points, try a line connecting first to second, third, ...
34+
let i = 0;
35+
for(let x = (1 << i); i < n; ++i, x <<= 1) {
36+
if ((mask & x) == 0) {
37+
break;
38+
}
39+
}
40+
for(let j = i + 1, x = (1 << j); j < n; ++j, x <<= 1) {
41+
if ((mask & x) == 0) {
42+
let mask2 = mask | connects[i][j];
43+
dp[mask] = Math.min(dp[mask], 1 + helper(n, mask2, dp, connects));
44+
}
45+
}
46+
}
47+
}
48+
return dp[mask];
49+
}
50+
51+
function numOfOne(num) {
52+
const str = (num >>> 0).toString(2)
53+
let res = 0
54+
for(let ch of str) {
55+
if(ch === '1') res++
56+
}
57+
return res
58+
}

0 commit comments

Comments
 (0)