265.Paint-House-II
265. Paint House II
题目地址
https://leetcode.com/problems/paint-house-ii/
题目描述
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.
Example:
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.
Follow up:
Could you solve it in O(nk) runtime?代码
Approach #1 DFS + Memoization
Time complexity : O(nk^2) && Space complexity : O(n⋅k)
Approach #2 Dynamic Programming
Time complexity : O(nk^2) && Space complexity : O(1)
Approach #3 Dynamic Programming with Optimized Time
如果最小值是第i个元素,次小值是第j个元素
如果除掉的元素不是第i个,剩下的最小值就是第i个元素
如果除掉的是第i个,剩下的最小值就是第j个元素
Time complexity : O(nk) && Space complexity : O(1)
Last updated
Was this helpful?