Leetcode - Paint House

My code:

public class Solution {
    public int minCost(int[][] costs) {
        if (costs == null || costs.length == 0 || costs[0].length != 3) {
            return 0;
        }
        
        int[][] cache = new int[costs.length][costs[0].length];
        int min = Integer.MAX_VALUE;
        min = Math.min(min, helper(0, 0, costs, cache));
        min = Math.min(min, helper(0, 1, costs, cache));
        min = Math.min(min, helper(0, 2, costs, cache));
        return min;
    }
    
    
    private int helper(int index, int currColor, int[][] costs, int[][] cache) {
        if (index >= costs.length) {
            return 0;
        }
        int cost = 0;
        if (cache[index][currColor] != 0) {
            return cache[index][currColor];
        }
        cost += costs[index][currColor];
        int min = Integer.MAX_VALUE;
        if (currColor != 0) {
            min = Math.min(min, helper(index + 1, 0, costs, cache));
        }
        if (currColor != 1) {
            min = Math.min(min, helper(index + 1, 1, costs, cache));
        }
        if (currColor != 2) {
            min = Math.min(min, helper(index + 1, 2, costs, cache));
        }
        cache[index][currColor] = cost + min;
        return cost + min;
    }
    
    public static void main(String[] args) {
        Solution test = new Solution();
        int[][] costs = new int[][]{{20, 18, 4}, {9, 9, 10}};
        int ret = test.minCost(costs);
        System.out.println(ret);
    }
}

看到这道题目,我第一个想到的是
** backtracking + memory cache **

然后写了出来。
速度还是比较慢的。

看了答案,原来有 Greedy 的做法.

My code:

public class Solution {
    public int minCost(int[][] costs) {
        if (costs == null || costs.length == 0 || costs[0].length != 3) {
            return 0;
        }
        
        int lastRed = costs[0][0];
        int lastBlue = costs[0][1];
        int lastGreen = costs[0][2];
        
        for (int i = 1; i < costs.length; i++) {
            int currRed = Math.min(lastBlue, lastGreen) + costs[i][0];
            int currBlue = Math.min(lastRed, lastGreen) + costs[i][1];
            int currGreen = Math.min(lastRed, lastBlue) + costs[i][2];
            
            lastRed = currRed;
            lastBlue = currBlue;
            lastGreen = currGreen;
        }
        
        return Math.min(lastRed, Math.min(lastBlue, lastGreen));
    }
    
    public static void main(String[] args) {
        Solution test = new Solution();
        int[][] costs = new int[][]{{20, 18, 4}, {9, 9, 10}};
        int ret = test.minCost(costs);
        System.out.println(ret);
    }
}

reference:
https://discuss.leetcode.com/topic/32408/share-my-very-simple-java-solution-with-explanation

lastRed 表示上一层涂红色所造成的最小开销
。。。

然后一层层往下递推,只需要最小的开销。
时间复杂度 O(3 * N)
而我backtracking 的时间复杂是: O(M* N), 虽然有cache使得速度变快,但无法改变他的时间复杂度。

Anyway, Good luck, Richardo! — 09/20/2016

    原文作者:Richardo92
    原文地址: https://www.jianshu.com/p/a40e459706eb#comments
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞