Skip to content

Prepare For Coder Interview – Denny

  • Basic
  • Medium
  • Hard
  • Architect
  • Life

Leetcode: Paint House

Posted on February 14, 2018September 23, 2019 by braindenny

Paint House



Similar Problems:

  • Series: Paint Fence & Follow-up
  • Paint Fence
  • CheatSheet: Leetcode For Code Interview
  • Tag: #dynamicprogramming, #paintfence

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.

Github: code.dennyzhang.com

Credits To: leetcode.com

Leave me comments, if you have better ways to solve.


## https://code.dennyzhang.com/paint-house
## Basic Ideas: Dyanmic programming
##     For house after house1, it can only have 3 possilities.
##
## Complexity: Time O(n), Space O(1)
class Solution:
    def minCost(self, costs):
        """
        :type costs: List[List[int]]
        :rtype: int
        """
        length = len(costs)
        if length == 0: return 0

        dp = [None]*3

        # caculate house I
        dp = costs[0]

        # caculate the following house
        for i in range(1, length):
            l = [None]*3
            for j in range(0, 3):
                l[j] = costs[i][j] + min(dp[(j+1)%3], dp[(j+2)%3])
            dp = l
        return min(dp)
linkedin
github
slack

Post Views: 5
Posted in MediumTagged #dynamicprogramming, #inspiring, paintfence

Post navigation

Leetcode: Find Minimum in Rotated Sorted Array II
Leetcode: Flatten 2D Vector

Leave a Reply Cancel reply

Your email address will not be published.

Tags

#array #backtracking #bfs #binarytree #bitmanipulation #classic #codetemplate #combination #dfs #dynamicprogramming #game #graph #greedy #heap #inspiring #interval #linkedlist #manydetails #math #misc #palindrome #recursive #slidingwindow #stack #string #subarray #trie #twopointer #twosum baseconversion binarysearch editdistance hashmap knapsack monotone oodesign presum redo review rotatelist series sql topologicalsort treetraversal unionfind

Recent Posts

  • Leetcode: Palindrome Partitioning III
  • Leetcode: Biggest Single Number
  • Leetcode: Max Consecutive Ones II
  • Leetcode: Minimum Cost to Connect Sticks
  • Leetcode: Minimum Swaps to Group All 1’s Together

Recent Comments

    Archives

    Categories

    • Amusing
    • Basic
    • Easy
    • Hard
    • Life
    • Medium
    • Resource
    • Review
    • Series
    • Uncategorized
    Proudly powered by WordPress | Theme: petals by Aurorum.