[LinkedIn]Min cost of paint house with color

见过在onsite的居多

Given a list of houses and the cost of painting each house, the houses can be painted in three colors RED, GREEN and BLUE, two neighboring houses can’t be painted in the same color, calculate the total minimum cost for painting all houses.

解法:

1) Dynamic programming problem.
2)Maintain a array of min cost called min_cost, each column represent a color and each row represent a houses.
3) min_cost[i][0] represents that, when the ith house is painted Red, the min cost of 0 to ith houses. Thus we have the following:

min_cost{i} = min(
//since the current color cannot be the same as the previous one
cost[i][R] + min(cost{i-1, B}, cost{i-1, G}),
cost[i][B] + min(cost{i-1, R}, cost{i-1, G}),
cost[i][G] + min(cost{i-1, R}, cost{i-1, B})
)

/*
 *  Code:
 */
//cost is a #_of_house x 3 array
public int minPaintCost(int[][] cost) {
    if (cost == null || cost.length == 0) return 0;
    int[][] dp = new int[cost.length][3];
    dp[0][0] = cost[0][0], dp[0][1] = cost[0][1], dp[0][2] = cost[0][2];
    for (int i = 1; i < cost.length; ++i) {
        dp[i][0] = cost[i][0] + Math.min(dp[i-1][1], dp[i-1][2]);
        dp[i][1] = cost[i][1] + Math.min(dp[i-1][0], dp[i-1][2]);
        dp[i][2] = cost[i][2] + Math.min(dp[i-1][0], dp[i-1][1]);
    }
    return Math.min(dp[dp.length-1][0], Math.min(dp[dp.length-1][1],[dp.length-1][2]));
}

转载于:https://www.cnblogs.com/jxlgetter/p/4395072.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值