leetcode 265. Paint House II (Python)

Leetcode 265. Paint House II (Python)

Related Topic

Dynamic-Programming.

Description

There are a row of n houses, each house can be painted with one of the k colors. 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 k cost matrix. For example, costs[0][0] is the cost of painting house 0 with color 0; costs[1][2] is the cost of painting house 1 with color 2, and so on… Find the minimum cost to paint all houses.

Sample I/O

Example 1

Input: [[1,5,3],[2,9,4]]
Output: 5
Explanation: Paint house 0 into color 0, paint house 1 into color 2. Minimum cost: 1 + 4 = 5; Or paint house 0 into color 2, paint house 1 into color 0. Minimum cost: 3 + 2 = 5. 

Note:

All costs are positive integers.

Follow up:

Could you solve it in O(nk) runtime?

Methodology

This question solved by Dynamic Programming. It is similar with question 256. Paint House. The difference is color options get expand to k now.

  1. Find the pattern:

    The pattern should be just same as question 256 but we need one more step to iterate the color options.

Code

size = len(costs)
        if size == 0: return 0
        if size == 1: return min(costs[0])
        colors = costs[0]
        k = len(colors)
        for i in range(1, size):
            for j in range(k):
                pre_house = costs[i-1]
                costs[i][j]+=min(pre_house[:j]+pre_house[j+1:])
        return min(costs[-1])

BigO

We iterate all costs list O(n). for each cost in costs list, we need to iterate all the color options except the current option O(k-1), in total will be O(n(k-1)) and It is O(nk)

Search

    Table of Contents