Approach
Depth-first search
For Minimum Number of Lines to Cover Points, the implementation follows one branch at a time, making it suitable for components, trees, backtracking, or dependency exploration.
- Define the state carried into one recursive or stack frame.
- Mark or choose the current state before exploring children.
- Combine child results or undo the choice when the branch finishes.
Code notes
- 55 lines of Java from the credited upstream file 2152.java.
- The implementation visibly relies on sequence storage.
- 3 loop blocks detected, together with recursive traversal.
Complexity
Count unique states for graph traversal; for backtracking, count the branching factor and maximum depth.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class Solution {2 public int minimumLines(int[][] points) {3 final int allCovered = (1 << points.length) - 1;4 int[] mem = new int[allCovered];5 Arrays.fill(mem, -1);6 return dfs(points, 0, allCovered, mem);7 }8 9 private int dfs(int[][] points, int covered, int allCovered, int[] mem) {10 if (covered == allCovered)11 return 0;12 if (mem[covered] != -1)13 return mem[covered];14 15 final int n = points.length;16 int ans = n / 2 + ((n & 1) == 1 ? 1 : 0);17 18 for (int i = 0; i < n; ++i) {19 if ((covered >> i & 1) == 1)20 continue;21 for (int j = 0; j < n; ++j) {22 if (i == j)23 continue;24 25 int newCovered = covered | 1 << i | 1 << j;26 27 Pair<Integer, Integer> slope = getSlope(points[i], points[j]);28 for (int k = 0; k < n; ++k)29 if (getSlope(points[i], points[k]).equals(slope))30 newCovered |= 1 << k;31 ans = Math.min(ans, 1 + dfs(points, newCovered, allCovered, mem));32 }33 }34 35 return mem[covered] = ans;36 }37 38 private Pair<Integer, Integer> getSlope(int[] p, int[] q) {39 final int dx = p[0] - q[0];40 final int dy = p[1] - q[1];41 if (dx == 0)42 return new Pair<>(0, p[0]);43 if (dy == 0)44 return new Pair<>(p[1], 0);45 final int d = gcd(dx, dy);46 final int x = dx / d;47 final int y = dy / d;48 return x > 0 ? new Pair<>(x, y) : new Pair<>(-x, -y);49 }50 51 private int gcd(int a, int b) {52 return b == 0 ? a : gcd(b, a % b);53 }54}55