zoukankan      html  css  js  c++  java
  • 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 }
  • 相关阅读:
    github提交用户权限被拒
    vue数据响应式的一些注意点
    总结一下做移动端项目遇到的坑
    react-router
    promise-async-await
    递归函数
    Linux基础
    所有的数据处理都是map-reduce
    Mac下配置JAVA_HOME
    MySQL高级
  • 原文地址:https://www.cnblogs.com/EdwardLiu/p/4346139.html
Copyright © 2011-2022 走看看