Minimum Number of Lines to Cover Points — LeetCode 2152 Python Solution
- Problem
- #2152
- Pattern
- Backtracking
- Reading time
- 5 min
- Source
- leetcode.com
The problem
You are given an array points where points[i] = [xi, yi] 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.
Example
- 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:
Python solution
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)
@cache
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)Complexity
| Measure | Complexity |
|---|---|
| Time | O(n) |
| Space | O(n) auxiliary |
Pattern: Backtracking
Build candidates one choice at a time and abandon a branch the moment it cannot work. LeetCode 2152. Minimum Number of Lines to Cover Points is filed here because LeetCode tags it Backtracking, which is the vocabulary this hub collects.
The backtracking guide has the Python template for the pattern and the 105 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 2152. Minimum Number of Lines to Cover Points?
- LeetCode 2152. Minimum Number of Lines to Cover Points is rated Medium on LeetCode.
- What is the time complexity of LeetCode 2152. Minimum Number of Lines to Cover Points?
- The Python solution on this page runs in O(n).
- What is the space complexity of LeetCode 2152. Minimum Number of Lines to Cover Points?
- The Python solution on this page uses O(n) auxiliary space.
- What topics does LeetCode 2152. Minimum Number of Lines to Cover Points cover?
- LeetCode 2152. Minimum Number of Lines to Cover Points is tagged Bit Manipulation, Geometry, Array, Hash Table, Math, Dynamic Programming, Backtracking and Bitmask on LeetCode.
- Is LeetCode 2152. Minimum Number of Lines to Cover Points a premium problem?
- Yes. LeetCode 2152. Minimum Number of Lines to Cover Points is a LeetCode Premium problem, so the full statement and test cases require a paid LeetCode subscription.