PaintHouseOPT [source code]

public class PaintHouseOPT {
    public int minCost(int[][] costs) {
        if (costs.length == 0) return 0;
        int lastR = costs[0][0];
        int lastG = costs[0][1];
        int lastB = costs[0][2];
        for (int i = 1; i < costs.length; i++) {
            int curR = Math.min(lastG,lastB) + costs[i][0];
            int curG = Math.min(lastR,lastB) + costs[i][1];
            int curB = Math.min(lastR,lastG) + costs[i][2];
            lastR = curR;
            lastG = curG;
            lastB = curB;
        }
        return Math.min(Math.min(lastR,lastG), lastB);
    }
}

这个是 submission 最优解, 1ms, 51%;

前面讲了bottom-up在这个问题上的帮助, 但是这个并不是所有的优化就结束了. 在425上课的时候就介绍了一个追加的优化(虽然只是稍微提了一下), 就是在这个问题, 如果我们需要的只是一个最后的结果, 那么我们实际上不需要维护整个 table, 而真正对我们有用的其实只有上一行的信息; 而这里的第二维又不大, 所以干脆就直接用几个 buffer 来保存上一行的信息就行了;

这个优化不仅做到了space 大幅减少, 而且还意外的对 time 也进行了加速;

当然, 达到这个目的, discussion 里面有一个人还利用了另外一种思路, 也是我们之前提到过的一种减少 space 的常用思路: 直接 reuse input, 也就是这个人直接把 costs 作为 table 来使用;


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

results matching ""

    No results matching ""