GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing github.com — [LeetCode] 256. Paint House · Issue #256 · grandyang/leetcode Open Description
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 Note: Example:
这道题说有n个房子,每个房子可以用红绿蓝三种颜色刷,每个房子的用每种颜色刷的花费都不同,限制条件是相邻的房子不能用相同的颜色来刷,现在让求刷完所有的房子的最低花费是多少。这题跟 House Robber II 和 House Robber 很类似,不过那题不是每个房子都抢,相邻的房子不抢,而这道题是每个房子都刷,相邻的房子不能刷同一种颜色,而 Paint Fence 那道题主要考察有多少种刷法。这几道题很类似,但都不一样,需要分别区分。但是它们的解题思想都一样,需要用动态规划 Dynamic Programming 来做,这道题需要维护一个二维的动态数组 dp,其中 dp[i][j] 表示刷到第 i+1 房子用颜色j的最小花费,状态转移方程为: dp[i][j] = dp[i][j] + min(dp[i - 1][(j + 1) % 3], dp[i - 1][(j + 2) % 3]); 这个也比较好理解,如果当前的房子要用红色刷,则上一个房子只能用绿色或蓝色来刷,那么要求刷到当前房子,且当前房子用红色刷的最小花费就等于当前房子用红色刷的钱加上刷到上一个房子用绿色和刷到上一个房子用蓝色中的较小值,这样当算到最后一个房子时,只要取出三个累计花费的最小值即可,参见代码如下:
解法一:
由于只有红绿蓝三张颜色,所以就可以分别写出各种情况,这样写可能比上面的写法更加一目了然一些,更容易理解一点吧:
解法二:
Github 同步地址:
类似题目:
参考资料: https://leetcode.com/problems/paint-house/ https://leetcode.com/problems/paint-house/discuss/68211/Simple-java-DP-solution
Activity
MetadataMetadataAssigneesLabelsNo labels TypeProjectsMilestoneRelationshipsDevelopmentIssue actions |
| You are visitor 01402775 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |