1. 程式人生 > >painting house

painting house

imu itl pos clas adjust 一個 have ted there

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