|
| 1 | +/* |
| 2 | +Paint House II |
| 3 | +============= |
| 4 | +
|
| 5 | +There are a row of n houses, each house can be painted with one of the k colors. The cost of painting each house with a certain color is different. You have to paint all the houses such that no two adjacent houses have the same color. |
| 6 | +
|
| 7 | +The cost of painting each house with a certain color is represented by an n x k cost matrix costs. |
| 8 | +
|
| 9 | +For example, costs[0][0] is the cost of painting house 0 with color 0; costs[1][2] is the cost of painting house 1 with color 2, and so on... |
| 10 | +Return the minimum cost to paint all houses. |
| 11 | +
|
| 12 | +Example 1: |
| 13 | +Input: costs = [[1,5,3],[2,9,4]] |
| 14 | +Output: 5 |
| 15 | +Explanation: |
| 16 | +Paint house 0 into color 0, paint house 1 into color 2. Minimum cost: 1 + 4 = 5; |
| 17 | +Or paint house 0 into color 2, paint house 1 into color 0. Minimum cost: 3 + 2 = 5. |
| 18 | +
|
| 19 | +Example 2: |
| 20 | +Input: costs = [[1,3],[2,4]] |
| 21 | +Output: 5 |
| 22 | + |
| 23 | +Constraints: |
| 24 | +costs.length == n |
| 25 | +costs[i].length == k |
| 26 | +1 <= n <= 100 |
| 27 | +2 <= k <= 20 |
| 28 | +1 <= costs[i][j] <= 20 |
| 29 | + |
| 30 | +Follow up: Could you solve it in O(nk) runtime? |
| 31 | +*/ |
| 32 | + |
| 33 | +class Solution { |
| 34 | +public: |
| 35 | + int memo[101][22]; |
| 36 | + |
| 37 | + int dfs(vector<vector<int>>& costs, int i, int prev_color) { |
| 38 | + if(i == costs.size()) return 0; |
| 39 | + |
| 40 | + if(memo[i][prev_color+1] != -1) return memo[i][prev_color+1]; |
| 41 | + int ans = INT_MAX; |
| 42 | + |
| 43 | + for(int j=0; j<costs[i].size(); ++j) { |
| 44 | + if(prev_color != j) { |
| 45 | + int next = dfs(costs, i+1, j); |
| 46 | + if(next != INT_MAX) |
| 47 | + ans = min(ans, costs[i][j] + next); |
| 48 | + } |
| 49 | + } |
| 50 | + |
| 51 | + return memo[i][prev_color+1] = ans; |
| 52 | + } |
| 53 | + |
| 54 | + int minCostII(vector<vector<int>>& costs) { |
| 55 | + memset(memo, -1, sizeof memo); |
| 56 | + return dfs(costs, 0, -1); |
| 57 | + } |
| 58 | +}; |
| 59 | + |
0 commit comments