zoukankan      html  css  js  c++  java
  • 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);
                }
            }
        }
    

      

      

  • 相关阅读:
    Mybatis resultMap和resultType的区别
    根据xml文件生成javaBean
    WebService如何封装XML请求 以及解析接口返回的XML
    Java SE练习
    Maven手动将jar导入本地仓库
    【公告】【公告】【公告】【公告】
    【题解】SDOI2010地精部落
    【题解】CF559C C. Gerald and Giant Chess(容斥+格路问题)
    【题解】任务安排(斜率优化)
    【题解】Cats Transport (斜率优化+单调队列)
  • 原文地址:https://www.cnblogs.com/apanda009/p/7295247.html
Copyright © 2011-2022 走看看