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

Better Solution: O(N) time, O(1) space

The basic idea is when we have painted the first i houses, and want to paint the i+1 th house, we have 3 choices: paint it either red, or green, or blue. If we choose to paint it red, we have the follow deduction:

paintCurrentRed = min(paintPreviousGreen,paintPreviousBlue) + costs[i+1][0]

Same for the green and blue situation. And the initialization is set to costs[0], so we get the code:

public class Solution {
public int minCost(int[][] costs) {
    if(costs.length==0) return 0;
    int lastR = costs[0][0];
    int lastG = costs[0][1];
    int lastB = costs[0][2];
    for(int i=1; i<costs.length; i++){
        int curR = Math.min(lastG,lastB)+costs[i][0];
        int curG = Math.min(lastR,lastB)+costs[i][1];
        int curB = Math.min(lastR,lastG)+costs[i][2];
        lastR = curR;
        lastG = curG;
        lastB = curB;
    }
    return Math.min(Math.min(lastR,lastG),lastB);
}

 打印所有的优化路径:

public void dfs(List<List<Integer>> ans, List<Integer> list, int[][] costs, int last,
                                   int sum, int pos, int min) {
        if (pos == costs.length) {
            if (sum == min) {
                ans.add(new ArrayList<>(list));
            }
            return;
        }
        for (int i = 0; i < costs[0].length; i++) {
            if (i != last) {
                list.add(i);
                dfs(ans, list, costs, i, sum + costs[pos][i], pos + 1, min);
                list.remove(list.size() - 1);
            }
        }
    }

  

  

原文地址:https://www.cnblogs.com/apanda009/p/7295247.html