1. Recursive Subset Search
Intuition
Sort pairs by start coordinate, then recursively test including or excluding each pair while tracking the last chosen end coordinate.
Algorithm
- Step 1: Sort pairs ascending by start coordinate.
- Step 2: Define recursive function solve(idx, lastEnd).
- Step 3: If idx == n, return 0.
- Step 4: Compute notTake = solve(idx + 1, lastEnd).
- Step 5: If pairs[idx][0] > lastEnd, take = 1 + solve(idx + 1, pairs[idx][1]).
- Step 6: Return max(take, notTake).
Enumerate All Subsets of Pairs
2 of 2 questions left todayPair [1,2] can be followed by [7,8] since 2 < 7
Pair [1,2] can be followed by [7,8] since 2 < 7.
#include <iostream>#include <vector>#include <algorithm> using namespace std; class Solution { int solve(int idx, int lastEnd, const vector<vector<int>>& pairs) { if (idx == pairs.size()) return 0; int notTake = solve(idx + 1, lastEnd, pairs); int take = 0; if (pairs[idx][0] > lastEnd) { take = 1 + solve(idx + 1, pairs[idx][1], pairs); } return max(take, notTake); }public: int findLongestChain(vector<vector<int>>& pairs) { sort(pairs.begin(), pairs.end()); return solve(0, -1e9, pairs); }}; int main() { Solution sol; vector<vector<int>> pairs = {{1, 2}, {7, 8}, {4, 5}, {2, 3}}; cout << "Longest Chain: " << sol.findLongestChain(pairs) << endl; return 0;}Time & Space Complexity
- Time complexity:
O(2^N) - Space complexity:
O(N)