leetcode:動態規劃( hard )
leetcode 265 Paint House II
problem:
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.
Note:
All costs are positive integers.
Follow up:
Could you solve it in O(nk) runtime?
解題思路:
WTF!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
想不出來。這裡原來的3種顏色變成了K種,按照之前的寫法無法達到nk.去看了看大神的想法.晚點再補程式碼。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。
The idea is similar to the problem Paint House I, for each house and each color, the minimum cost of painting the house with that color should be the minimum cost of painting previous houses, and make sure the previous house doesn't paint with the same color.
We can use min1 and min2 to track the indices of the 1st and 2nd smallest cost till previous house, if the current color's index is same as min1, then we have to go with min2, otherwise we can safely go with min1.
The code below modifies the value of costs[][] so we don't need extra space.
相關文章
- [leetcode] 動態規劃(Ⅰ)LeetCode動態規劃
- leetcode總結——動態規劃LeetCode動態規劃
- leetcode題解(動態規劃)LeetCode動態規劃
- LeetCode動態規劃總結LeetCode動態規劃
- 【LeetCode】Word Break 動態規劃LeetCode動態規劃
- 【leetcode】741 摘櫻桃(動態規劃)LeetCode動態規劃
- leetcode-動態規劃總結LeetCode動態規劃
- 【LeetCode】Word Break II 動態規劃LeetCode動態規劃
- 【動態規劃(一)】動態規劃基礎動態規劃
- [LeetCode] 動態規劃題型總結LeetCode動態規劃
- Leetcode 編輯距離(動態規劃)LeetCode動態規劃
- LeetCode 動態規劃 House Robber 習題LeetCode動態規劃
- [leetcode 1235] [動態規劃]LeetCode動態規劃
- 動態規劃動態規劃
- LeetCode 分割回文串II(動態規劃)LeetCode動態規劃
- LeetCode入門指南 之 動態規劃思想LeetCode動態規劃
- LeetCode:動態規劃+貪心題目整理LeetCode動態規劃
- LeetCode 343. 整數拆分--動態規劃LeetCode動態規劃
- 【LeetCode】55. 跳躍遊戲 (動態規劃)LeetCode遊戲動態規劃
- 動態規劃分析動態規劃
- 動態規劃(DP)動態規劃
- 動態規劃初步動態規劃
- 模板 - 動態規劃動態規劃
- 動態規劃法動態規劃
- Leetcode 題解演算法之動態規劃LeetCode演算法動態規劃
- LeetCode總結,動態規劃問題小結LeetCode動態規劃
- 演算法系列-動態規劃(1):初識動態規劃演算法動態規劃
- [leetcode初級演算法]動態規劃總結LeetCode演算法動態規劃
- 【LeetCode】Wildcard Matching 串匹配 動態規劃LeetCode動態規劃
- 淺談動態規劃動態規劃
- 有關動態規劃動態規劃
- 動態規劃小結動態規劃
- 動態規劃初級動態規劃
- 動態規劃講義動態規劃
- 好題——動態規劃動態規劃
- 3.動態規劃動態規劃
- 動態規劃-----線性動態規劃
- 動態規劃專題動態規劃