首页 > 代码库 > painting house
painting house
There are a row of houses, each house can be painted with three colors red, blue and 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. You have to paint the houses with minimum cost. How would you do it? Note: Painting house-1 with red costs different from painting house-2 with red. The costs are different for each house and each color.
一个dp,f(i,j)表示前i个house都paint了且第i个house paint成color_j的最小cost。
背包问题同 Minimum Adjustment Cost
int paint(int N, int M, int[][] cost) { int[][] res = new int[N+1][M]; for (int t=0; t<M; t++) { res[0][t] = 0; } for (int i=1; i<N; i++) { for (int j=0; j<M; j++) { res[i][j] = Integer.MAX_VALUE; } } for (int i=1; i<=N; i++) { for (int j=0; j<M; j++) { for (int k=0; k<M; k++) { if (k != j) { res[i][j] = Math.min(res[i][j], res[i-1][k]+cost[i-1][j]); // } } } } int result = Integer.MAX_VALUE; for (int t=0; t<M; t++) { result = Math.min(result, res[N][t]); } return result; }
painting house
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。