1. Recursive Interval Cover Search
Intuition
Sort balloons and recursively evaluate shooting an arrow at each candidate endpoint or trying subsequent intervals.
Algorithm
- Step 1: Sort points by end coordinate.
- Step 2: Define recursive solve(idx, lastArrow) returning min arrows from idx onwards.
- Step 3: If idx == n, return 0.
- Step 4: If points[idx][0] <= lastArrow, balloon is already burst -> solve(idx + 1, lastArrow).
- Step 5: Otherwise, shoot at points[idx][1] -> 1 + solve(idx + 1, points[idx][1]).
- Step 6: Return result.
Enumerate Candidate Shooting Points
2 of 2 questions left todayEvaluate coordinate x = 2
Evaluate coordinate x = 2. It pierces balloons spanning through 2, namely [1,6] and [2,8].
#include <iostream>#include <vector>#include <algorithm> using namespace std; class Solution { int solve(int idx, long long lastArrow, const vector<vector<int>>& points) { if (idx == points.size()) return 0; if (points[idx][0] <= lastArrow) { return solve(idx + 1, lastArrow, points); } return 1 + solve(idx + 1, points[idx][1], points); }public: int findMinArrowShots(vector<vector<int>>& points) { sort(points.begin(), points.end(), [](const vector<int>& a, const vector<int>& b) { return a[1] < b[1]; }); return solve(0, -3e18, points); }}; int main() { Solution sol; vector<vector<int>> points = {{10, 16}, {2, 8}, {1, 6}, {7, 12}}; cout << "Min Arrows: " << sol.findMinArrowShots(points) << endl; return 0;}Time & Space Complexity
- Time complexity:
O(2^N) - Space complexity:
O(N)