Minimum Number of Lines to Cover Points Problem
Description
LeetCode Problem 2152.
You are given an array points where points[i] = [x_i, y_i] represents a point on an X-Y plane.
Straight lines are going to be added to the X-Y plane, such that every point is covered by at least one line.
Return the minimum number of straight lines needed to cover all the points.
Example 1:

Input: points = [[0,1],[2,3],[4,5],[4,3]]
Output: 2
Explanation: The minimum number of straight lines needed is two. One possible solution is to add:
- One line connecting the point at (0, 1) to the point at (4, 5).
- Another line connecting the point at (2, 3) to the point at (4, 3).
Example 2:

Input: points = [[0,2],[-2,-2],[1,4]]
Output: 1
Explanation: The minimum number of straight lines needed is one. The only solution is to add:
- One line connecting the point at (-2, -2) to the point at (1, 4).
Constraints:
1 <= points.length <= 10points[i].length == 2-100 <= x_i, y_i <= 100- All the
pointsare unique.
Solution
Approach: State Compression + Memoized Search
There are at most 10 points, so use a bitmask state for the points already covered. Let dfs(state) be the minimum number of extra lines needed.
If every point is covered, return 0. Otherwise take each uncovered point i and pair it with a later point j. The line through i and j also covers every other point k that is collinear with them (checked with a cross product, so no division is needed); add those to the mask and recurse. If the last point n - 1 is still uncovered on its own, a single line through it alone is also a choice. The answer is dfs(0), with results cached per mask.
Complexity: O(2^n * n^3) time and O(2^n) extra space.
from functools import lru_cache
from math import inf
class Solution:
def minimumLines(self, points: List[List[int]]) -> int:
def check(i, j, k):
x1, y1 = points[i]
x2, y2 = points[j]
x3, y3 = points[k]
return (x2 - x1) * (y3 - y1) == (x3 - x1) * (y2 - y1)
@lru_cache(None)
def dfs(state):
if state == (1 << n) - 1:
return 0
ans = inf
for i in range(n):
if not (state >> i & 1):
for j in range(i + 1, n):
nxt = state | 1 << i | 1 << j
for k in range(j + 1, n):
if not (nxt >> k & 1) and check(i, j, k):
nxt |= 1 << k
ans = min(ans, dfs(nxt) + 1)
if i == n - 1:
ans = min(ans, dfs(state | 1 << i) + 1)
return ans
n = len(points)
return dfs(0)