Paint House II 解答
2015-11-09 05:21
393 查看
Question
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 kcost 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?
Solution
这里时间复杂度是O(nk),说明要求我们用O(k)的时间计算每一层的新的cost。cost'[i] = costs[m][i] + min{cost[0], cost[1], ..., cost[i - 1], cost[i + 1], ..., cost[k - 1]}
原想法是对每一个i重新计算,时间复杂度是O(k2)。包含了大量的重复计算
其实我们只需求出cost[]序列的最小值和第二小的值。Time complexity O(k)
public class Solution { public int minCostII(int[][] costs) { if (costs == null || costs.length < 1) { return 0; } int m = costs.length, k = costs[0].length; int[] cost = new int[k]; int[] tmp = new int[k]; for (int i = 0; i < k; i++) { cost[i] = costs[m - 1][i]; } for (int i = m - 2; i >= 0; i--) { // calculate most and second minimum number int[] min = calcMin(cost); for (int j = 0; j < k; j++) { // if cost[j] is minimum, then add second minimum with costs[i][j] if (cost[j] == min[0]) { cost[j] = min[1] + costs[i][j]; } else { // if cost[j] is not minimum, then add minimum with costs[i][j] cost[j] = min[0] + costs[i][j]; } } } if (k < 2) { return cost[0]; } int[] result = calcMin(cost); return result[0]; } private int[] calcMin(int[] nums) { if (nums == null || nums.length < 2) { return new int[0]; } int[] mins = new int[2]; mins[0] = Math.min(nums[0], nums[1]); mins[1] = Math.max(nums[0], nums[1]); for (int i = 2; i < nums.length; i++) { if (nums[i] < mins[0]) { mins[1] = mins[0]; mins[0] = nums[i]; } else if (nums[i] < mins[1]) { mins[1] = nums[i]; } } return mins; } }
相关文章推荐
- Paint House 解答
- Daily Scrum meeting 2015.11.9
- 解读:全国100强企业为何选择TurboMail邮件系统
- weak和Strong,assign和retain和copy的区别
- 【Alpha】Daily Scrum Meeting第六次
- 【Alpha】Daily Scrum Meeting第六次
- Daily Scrum (2015/11/7)
- 【设计模式】Filter-Chain 的应用
- 【小玩意儿:在页面上设置链接发送E-mail】
- [leetcode] 219 Contains Duplicate II(map)
- zabbix设置sendmail发送邮件
- zabbix设置sendmail发送邮件
- Jetbrains的产品对在校学生免费
- HDU 4012Paint on a Wall
- QWidget、QMainWindow、QDialog区别
- HDU 1401 Solitaire
- Aizu 2595(容斥原理)
- Is there any datasheet,specification for adreno,krait
- 简单计算器的C实现-函数指针,main函数传参
- Rails中的validate校验