|
| 1 | +/** |
| 2 | + * 1595. Minimum Cost to Connect Two Groups of Points |
| 3 | + * https://leetcode.com/problems/minimum-cost-to-connect-two-groups-of-points/ |
| 4 | + * Difficulty: Hard |
| 5 | + * |
| 6 | + * You are given two groups of points where the first group has size1 points, the second group |
| 7 | + * has size2 points, and size1 >= size2. |
| 8 | + * |
| 9 | + * The cost of the connection between any two points are given in an size1 x size2 matrix where |
| 10 | + * cost[i][j] is the cost of connecting point i of the first group and point j of the second group. |
| 11 | + * The groups are connected if each point in both groups is connected to one or more points in the |
| 12 | + * opposite group. In other words, each point in the first group must be connected to at least one |
| 13 | + * point in the second group, and each point in the second group must be connected to at least one |
| 14 | + * point in the first group. |
| 15 | + * |
| 16 | + * Return the minimum cost it takes to connect the two groups. |
| 17 | + */ |
| 18 | + |
| 19 | +/** |
| 20 | +* @param {number[][]} cost |
| 21 | +* @return {number} |
| 22 | +*/ |
| 23 | +var connectTwoGroups = function(cost) { |
| 24 | + const size1 = cost.length; |
| 25 | + const size2 = cost[0].length; |
| 26 | + |
| 27 | + const minCostGroup2 = new Array(size2).fill(Infinity); |
| 28 | + for (let j = 0; j < size2; j++) { |
| 29 | + for (let i = 0; i < size1; i++) { |
| 30 | + minCostGroup2[j] = Math.min(minCostGroup2[j], cost[i][j]); |
| 31 | + } |
| 32 | + } |
| 33 | + |
| 34 | + const memo = new Array(size1).fill(0).map(() => new Array(1 << size2).fill(-1)); |
| 35 | + |
| 36 | + return dfs(0, 0); |
| 37 | + |
| 38 | + function dfs(i, mask) { |
| 39 | + if (i === size1) { |
| 40 | + let remainingCost = 0; |
| 41 | + for (let j = 0; j < size2; j++) { |
| 42 | + if ((mask & (1 << j)) === 0) { |
| 43 | + remainingCost += minCostGroup2[j]; |
| 44 | + } |
| 45 | + } |
| 46 | + return remainingCost; |
| 47 | + } |
| 48 | + |
| 49 | + if (memo[i][mask] !== -1) return memo[i][mask]; |
| 50 | + |
| 51 | + let minCost = Infinity; |
| 52 | + |
| 53 | + for (let j = 0; j < size2; j++) { |
| 54 | + minCost = Math.min( |
| 55 | + minCost, |
| 56 | + cost[i][j] + dfs(i + 1, mask | (1 << j)) |
| 57 | + ); |
| 58 | + } |
| 59 | + |
| 60 | + memo[i][mask] = minCost; |
| 61 | + return minCost; |
| 62 | + } |
| 63 | +}; |
0 commit comments