标签:

动态规划

题目描述:

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 0costs[1][2] is the cost of painting house 1with color 2, and so on... Find the minimum cost to paint all houses.

Example

Given n = 3, k = 3, costs =[[14,2,11],[11,14,5],[14,3,10]] return 10

house 0 is color 2, house 1 is color 3, house 2 is color 2,2 + 5 + 3 = 10

解题思路:

这两题较比之前的题目来讲要简单很多,子状态非常明显,转移方程非常容易得到

1.对于每一个房子,都k种设计方案。第n间房子的每种颜色的方案依赖于,第n-1间房子的其他颜色的最省钱方案。

2.初始状态,只有一间房子的时候,颜色价格方案是已知的。

参考代码:

public int minCostII(int[][] costs) {
// Write your code here
if(costs.length == 0||costs[0].length == 0) return 0;
int n = costs.length;
int k = costs[0].length; int[][] dp = new int[n][k];
for(int i = 0; i<k; i++){
dp[0][i] = costs[0][i];
} for(int i=1; i<n; i++){
for(int j = 0; j<k; j++){
int tmp_min = Integer.MAX_VALUE;
for(int m = 0; m<k; m++){
if(m==j){
continue;
}else{
tmp_min = Math.min(tmp_min, dp[i-1][m]);
}
}
dp[i][j] = tmp_min+costs[i][j];
}
} int min = Integer.MAX_VALUE;
for(int i=0; i<k; i++){
min = Math.min(min, dp[n-1][i]);
} return min;
}

最新文章

  1. 触发Full GC执行的情况
  2. openstack instance snapshort
  3. 点击listview 的列头对其item进行自动排序
  4. CPU,MPU,MCU,SOC,SOPC联系与差别
  5. zoj 1610 Count the Colors(线段树延迟更新)
  6. gameUnity 0.15alpha 网络游戏框架
  7. 第一个远程javaweb项目测试全过程
  8. nopCommerce 3.9 大波浪系列 之 IWebHelper
  9. XSS分析及如何预防
  10. MongoDB学习教程(1)
  11. Spring IOC容器分析(2) -- BeanDefinition
  12. 三、TensorFlow模型的保存和加载
  13. 宋宝华:关于Ftrace的一个完整案例【转】
  14. Java高并发--AQS
  15. goLand工程结构管理
  16. 用GDB调试程序(六)
  17. android AsyncHttpClient使用
  18. 20172302 《Java软件结构与数据结构》第四周学习总结
  19. [au3]复制选择性粘贴文本到excel
  20. Entity Framework 6.1.0 Tools for Visual Studio 2012 &amp; 2013

热门文章

  1. js正则笔记
  2. [Vue warn]: Failed to mount component: template or render function not defined. 错误解决方法
  3. html--伪等高布局
  4. Oracle Database 18c数据库安装步骤
  5. Java事件监听机制与观察者设计模式
  6. Mysql的数据列类型效率
  7. 8年前诞生于淘宝,细数阿里云RPA 的前世今生!
  8. springboot与任务(邮件任务)
  9. 19-11-10-Night
  10. Cesium官方教程9--粒子系统