1. Backtracking Simulation
Intuition
Branch recursively on all valid combinations of coins used for change at each transaction step to find if any combination serves all customers.
Algorithm
- Step 1: Define recursive function canServe(idx, fiveCount, tenCount).
- Step 2: If idx == n, all customers were served; return true.
- Step 3: If bill is $5: recurse with fiveCount + 1.
- Step 4: If bill is $10: require fiveCount >= 1; recurse with fiveCount - 1, tenCount + 1.
- Step 5: If bill is $20: try (tenCount >= 1 and fiveCount >= 1) branch OR (fiveCount >= 3) branch.
- Step 6: Return whether any branch succeeds.
#include <iostream>#include <vector> using namespace std; class Solution { bool canServe(int idx, int five, int ten, const vector<int>& bills) { if (idx == bills.size()) return true; int b = bills[idx]; if (b == 5) { return canServe(idx + 1, five + 1, ten, bills); } else if (b == 10) { if (five <= 0) return false; return canServe(idx + 1, five - 1, ten + 1, bills); } else { // b == 20 // Option 1: give 1 ten and 1 five if (ten >= 1 && five >= 1) { if (canServe(idx + 1, five - 1, ten - 1, bills)) return true; } // Option 2: give 3 fives if (five >= 3) { if (canServe(idx + 1, five - 3, ten, bills)) return true; } return false; } }public: bool lemonadeChange(vector<int>& bills) { return canServe(0, 0, 0, bills); }}; int main() { Solution sol; vector<int> bills1 = {5, 5, 5, 10, 20}; vector<int> bills2 = {5, 5, 10, 10, 20}; cout << boolalpha; cout << "bills1: " << sol.lemonadeChange(bills1) << endl; cout << "bills2: " << sol.lemonadeChange(bills2) << endl; return 0;}Time & Space Complexity
- Time complexity:
O(2^N) - Space complexity:
O(N)