• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
neverlandly
博客园    首页    新随笔    联系   管理    订阅  订阅

F面经: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。

 1 int paint(int N, int M, int[][] cost) {
 2     int[][] res = new int[N+1][M];
 3     for (int t=0; t<M; t++) {
 4         res[0][t] = 0;
 5     }
 6     for (int i=1; i<N; i++) {
 7         for (int j=0; j<M; j++) {
 8             res[i][j] = Integer.MAX_VALUE;
 9         }
10     }
11     for (int i=1; i<=N; i++) {
12         for (int j=0; j<M; j++) {
13             for (int k=0; k<M; k++) {
14                 if (k != j) {
15                     res[i][j] = Math.min(res[i][j], res[i-1][k]+cost[i-1][j]); //
16                 }
17             }
18         }
19     }
20     int result = Integer.MAX_VALUE;
21     for (int t=0; t<M; t++) {
22         result = Math.min(result, res[N][t]);
23     }
24     return result;
25 }

 

posted @ 2015-03-18 04:49  neverlandly  阅读(1616)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3