1. Recursive Exhaustive Search
Intuition
Recursively try painting each house with a color different from the previous house.
Algorithm
- Define
solve(house, prevColor). - If
house == n, return 0. - Try all colors
c in {0, 1, 2}wherec != prevColor. - Return
costs[house][c] + solve(house + 1, c). - Return min across all valid colorings.
#include <iostream>#include <vector>#include <algorithm> using namespace std; class Solution { int solve(int idx, int prevColor, const vector<vector<int>>& costs) { if (idx == costs.size()) return 0; int minCost = 1e9; for (int c = 0; c < 3; ++c) { if (c != prevColor) { minCost = min(minCost, costs[idx][c] + solve(idx + 1, c, costs)); } } return minCost; }public: int minCost(vector<vector<int>>& costs) { return solve(0, -1, costs); }}; int main() { Solution sol; vector<vector<int>> costs = {{17, 2, 17}, {16, 16, 5}, {14, 3, 19}}; cout << "Min Cost: " << sol.minCost(costs) << endl; return 0;}Time & Space Complexity
- Time complexity:
O(3 * 2^n) - Space complexity:
O(n) call stack