|
| 1 | +/** |
| 2 | + * 1473. Paint House III |
| 3 | + * https://leetcode.com/problems/paint-house-iii/ |
| 4 | + * Difficulty: Hard |
| 5 | + * |
| 6 | + * There is a row of m houses in a small city, each house must be painted with one of the n |
| 7 | + * colors (labeled from 1 to n), some houses that have been painted last summer should not |
| 8 | + * be painted again. |
| 9 | + * |
| 10 | + * A neighborhood is a maximal group of continuous houses that are painted with the same color. |
| 11 | + * |
| 12 | + * For example: houses = [1,2,2,3,3,2,1,1] contains 5 neighborhoods [{1}, {2,2}, {3,3}, {2}, {1,1}]. |
| 13 | + * |
| 14 | + * Given an array houses, an m x n matrix cost and an integer target where: |
| 15 | + * - houses[i]: is the color of the house i, and 0 if the house is not painted yet. |
| 16 | + * - cost[i][j]: is the cost of paint the house i with the color j + 1. |
| 17 | + * |
| 18 | + * Return the minimum cost of painting all the remaining houses in such a way that there are exactly |
| 19 | + * target neighborhoods. If it is not possible, return -1. |
| 20 | + */ |
| 21 | + |
| 22 | +/** |
| 23 | + * @param {number[]} houses |
| 24 | + * @param {number[][]} cost |
| 25 | + * @param {number} m |
| 26 | + * @param {number} n |
| 27 | + * @param {number} target |
| 28 | + * @return {number} |
| 29 | + */ |
| 30 | +var minCost = function(houses, cost, m, n, target) { |
| 31 | + const cache = new Map(); |
| 32 | + const result = findMinCost(0, 0, 0); |
| 33 | + return result === Infinity ? -1 : result; |
| 34 | + |
| 35 | + function findMinCost(index, prevColor, neighborhoods) { |
| 36 | + if (index === m) return neighborhoods === target ? 0 : Infinity; |
| 37 | + if (neighborhoods > target) return Infinity; |
| 38 | + |
| 39 | + const key = `${index}:${prevColor}:${neighborhoods}`; |
| 40 | + if (cache.has(key)) return cache.get(key); |
| 41 | + |
| 42 | + let minCost = Infinity; |
| 43 | + const currentColor = houses[index]; |
| 44 | + |
| 45 | + if (currentColor !== 0) { |
| 46 | + const newNeighborhoods = prevColor === currentColor ? neighborhoods : neighborhoods + 1; |
| 47 | + minCost = findMinCost(index + 1, currentColor, newNeighborhoods); |
| 48 | + } else { |
| 49 | + for (let color = 1; color <= n; color++) { |
| 50 | + const newNeighborhoods = prevColor === color ? neighborhoods : neighborhoods + 1; |
| 51 | + const currentCost = cost[index][color - 1] |
| 52 | + + findMinCost(index + 1, color, newNeighborhoods); |
| 53 | + minCost = Math.min(minCost, currentCost); |
| 54 | + } |
| 55 | + } |
| 56 | + |
| 57 | + cache.set(key, minCost); |
| 58 | + return minCost; |
| 59 | + } |
| 60 | +}; |
0 commit comments