/** * @param {number[]} houses * @param {number[][]} cost * @param {number} m * @param {number} n * @param {number} target * @return {number} */ var minCost = function(houses, cost, m, n, target) { houses = houses.map((c)=>--c); let dp = new Array(m).fill(0) .map(()=>new Array(n).fill(0) .map(()=>new Array(target).fill(Number.MAX_VALUE))); for(let i=0;i<m;i++){ for(let j=0;j<n;j++){ if(houses[i] != -1 && houses[i] != j){ continue; } for(let k = 0;k<target;k++){ for(let j0=0;j0<n;j0++){ if(j0 === j){ if(i===0){ if(k===0){ dp[i][j][k] = 0; } }else{ dp[i][j][k] = Math.min(dp[i][j][k], dp[i-1][j][k]); } }else if(i>0 && k>0){ dp[i][j][k] = Math.min(dp[i][j][k], dp[i-1][j0][k-1]); } } if(dp[i][j][k] !== Number.MAX_VALUE && houses[i] == -1){ dp[i][j][k] += cost[i][j]; } } } } let res = Number.MAX_VALUE; for(let j=0;j<n;j++){ res = Math.min(res, dp[m-1][j][target-1]); } return res === Number.MAX_VALUE?-1:res; }let houses = [0,0,0,0,0], cost = [[1,10],[10,1],[10,1],[1,10],[5,1]], m = 5, n = 2, target = 3 console.log(houses, cost, m,n,target, minCost(houses,cost,m,n,target)) houses = [3,1,2,3], cost = [[1,1,1],[1,1,1],[1,1,1],[1,1,1]], m = 4, n = 3, target = 3 console.log(houses, cost, m,n,target, minCost(houses,cost,m,n,target))