PU Paint House

Jan 01, 1970

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.

  • All costs are positive integers.

C Solution 1:

#define MIN(a, b) ((a) < (b) ? (a) : (b))

int minCost(int** costs, int costsRowSize, int costsColSize) {
    if (costsRowSize < 1) return 0;
    int i;
    for (i = 1; i < costsRowSize; i++) {
        costs[i][0] += MIN(costs[i - 1][1], costs[i - 1][2]);
        costs[i][1] += MIN(costs[i - 1][0], costs[i - 1][2]);
        costs[i][2] += MIN(costs[i - 1][0], costs[i - 1][1]);
    }
    return MIN(MIN(costs[i - 1][0], costs[i - 1][1]), costs[i - 1][2]);
}

C Solution 2:

#define MIN(a, b) ((a) < (b) ? (a) : (b))

int minCost(int** costs, int costsRowSize, int costsColSize) {
    int i, A = 0, B = 0, C = 0;
    for (i = 0; i < costsRowSize; i++) {
        int _A = costs[i][0] + MIN(B, C);
        int _B = costs[i][1] + MIN(A, C);
        int _C = costs[i][2] + MIN(A, B);
        A = _A, B = _B, C = _C;
    }
    return MIN(MIN(A, B), C);
}

Python Solution 1:

class Solution(object):
    def minCost(self, costs):
        """
        :type costs: List[List[int]]
        :rtype: int
        """
        if not costs: return 0
        for i in range(1, len(costs)):
            costs[i][0] += min(costs[i - 1][1], costs[i - 1][2])
            costs[i][1] += min(costs[i - 1][0], costs[i - 1][2])
            costs[i][2] += min(costs[i - 1][0], costs[i - 1][1])
        return min(costs[len(costs) - 1])

Python Solution 2:

class Solution(object):
    def minCost(self, costs):
        """
        :type costs: List[List[int]]
        :rtype: int
        """
        return min(reduce(lambda (A, B, C), (a, b, c): (a + min(B, C), b + min(A, C), c + min(A, B)), costs, [0] * 3))

Summary:

  • Solution and Good Solution.

LeetCode: 256. Paint House