The "Paint House"

Source: Internet
Author: User

Topic:

There is a row of n houses, each house can is painted with one of the three colors:red, blue or green. The cost of painting a certain color is different. You had to paint all the houses such, that no, and adjacent houses have the same color.

The cost of painting a certain color was represented by a cost n x 3 matrix. For example, was the cost of costs[0][0] painting House 0 with color red; costs[1][2] the cost of Painting House 1 with color green, And so on ... Find the minimum cost-to-paint all houses.

Note:
All costs is positive integers.

Links: http://leetcode.com/problems/paint-house/

Exercises

The house is painted with RGB paint, each paint for each house is not the same cost, requires two adjacent houses not a color, and the least cost. This problem to see the hint need to do with DP. At first I want to set a sum, a last color =-1, but there is no way to solve the problem of duplicate. So I still refer to the code of the Jianchao.li, the RGB respectively DP.

Time Complexity-o (n), Space complexity-o (1)

 Public classSolution { Public intMincost (int[] costs) {//DP        if(Costs = =NULL|| Costs.length = = 0) {            return0; }        intLen = costs.length, red = 0, blue = 0, green = 0;  for(inti = 0; i < costs.length; i++) {            intprevred = red, Prevblue = blue, Prevgreen =Green; Red= Costs[i][0] +math.min (Prevblue, Prevgreen); Blue= Costs[i][1] +math.min (prevred, Prevgreen); Green= Costs[i][2] +math.min (prevred, Prevblue); }                returnmath.min (Red, math.min (blue, green)); }}

Reference:

The "Paint House"

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.