方法1: dfs + memoization。时间复杂n,空间复杂n,n为房屋数量。
class Solution {
int red = -1;
int blue = 0;
int green = 1;
Map<Pair<Integer, Integer>, Integer> map = new HashMap<>();
public int minCost(int[][] costs) {
if(costs.length == 0) return 0;
int res1 = costs[0][0] + dfs(costs, 1, red);
int res2 = costs[0][1] + dfs(costs, 1, blue);
int res3 = costs[0][2] + dfs(costs, 1, green);
return Math.min(Math.min(res1, res2), res3);
}
public int dfs(int[][] costs, int i, int color){
if(map.containsKey(new Pair<>(i, color))) return map.get(new Pair<>(i, color));
if(i == costs.length) return 0;
int res = 0;
if(color == red){
res = Math.min(costs[i][1] + dfs(costs, i + 1, blue), costs[i][2] + dfs(costs, i + 1, green));
}
if(color == blue){
res = Math.min(costs[i][0] + dfs(costs, i + 1, red), costs[i][2] + dfs(costs, i + 1, green));
}
if(color == green){
res = Math.min(costs[i][0] + dfs(costs, i + 1, red), costs[i][1] + dfs(costs, i + 1, blue));
}
map.put(new Pair<>(i, color), res);
return res;
}
}
方法2: dp。时间复杂n,空间复杂1.
class Solution {
int RED = 0;
int BLUE = 1;
int GREEN = 2;
public int minCost(int[][] costs) {
if(costs.length == 0) return 0;
for(int i = 1; i < costs.length; i++){
for(int j = 0; j < 3; j++){
if(j == RED)
costs[i][j] = costs[i][j] + Math.min(costs[i - 1][BLUE], costs[i - 1][GREEN]);
if(j == BLUE)
costs[i][j] = costs[i][j] + Math.min(costs[i - 1][RED], costs[i - 1][GREEN]);
if(j == GREEN)
costs[i][j] = costs[i][j] + Math.min(costs[i - 1][RED], costs[i - 1][BLUE]);
}
}
int res = Integer.MAX_VALUE;
for(int i = 0; i < 3; i++){
res = Math.min(res, costs[costs.length - 1][i]);
}
return res;
}
}
总结:
- 这道题本身难度不是很大,但是复盘的时候希望自己可以耐心地好好地读完lc的官方解释,那是一篇很好的解释,会对你有帮助的,相信我。