PaintHouse [source code]
public class PaintHouse {
public int minCost(int[][] costs) {
int n = costs.length;
if (n == 0) return 0;
int[][] table = new int[n][3];
for (int i = 0; i < 3; i++) table[0][i] = costs[0][i];
for (int i = 1; i < n; i++) {
table[i][0] = Math.min(table[i - 1][1], table[i - 1][2]) + costs[i][0];
table[i][1] = Math.min(table[i - 1][0], table[i - 1][2]) + costs[i][1];
table[i][2] = Math.min(table[i - 1][0], table[i - 1][1]) + costs[i][2];
}
int res = Integer.MAX_VALUE;
for (int i : table[n - 1]) if (i < res) res = i;
return res;
}
}
optimization 问题, 基本也是往 DP 上面靠了;
这个问题跟当时463的时候的作业的第一题非常相似: 当前 level 的 decision 会对之前的 decision 产生影响; 理解这个问题有两个要点:
- 首先思考, 你的 table 有几个index, 以及每个 index 代表什么. 这里你的 table 一个 index, 也就是end position就够了吗? 很明显不够, 还要加一个 index: the color for the last house;
- 这个问题, bottom-up的思考方式其实比top-down更好理解; bottom-up结合二维 table, 理解起来比用 recursion 的观点top-down要直观的多;
代码对于empty case的处理一定要合适, 因为这个代码涉及到大量的array access;
这里犯了一个小错误, 就是 res 一开始的 init 又犯了低级错误. 所以这里如果 res 直接用 min 这个名字, 可能可以提醒自己在 init 的时候小心一点;
速度是2ms, 14%, 好像不算是特别快的;
Problem Description
There are a row of n houses, each house can be painted with one of the three colors: red, blue or green. 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.
The cost of painting each house with a certain color is represented by a n x 3 cost matrix. For example, costs[0][0] is the cost of painting house 0 with color red; costs[1][2] is the cost of painting house 1 with color green, and so on... Find the minimum cost to paint all houses.
Note:
All costs are positive integers.
Difficulty:Easy
Category:Algorithms
Acceptance:45.89%
Contributor: LeetCode
Companies
linkedin
Related Topics
dynamic programming
Similar Questions
House Robber House Robber II Paint House II Paint Fence