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);
                }
            }
        }
    

      

      

  • 相关阅读:
    关于域名备案申请
    meta标签中的http-equiv属性使用介绍
    WDCP3.3中多PHP版本安装方法,以及安装遇到的问题
    模拟《意尔康》网站加载动画效果
    如何提示系统所在的浏览器版本过低?
    Dedecms升级php版本{dede:field.body/}不解析,文章内容不显示
    微信weixin://xxx 分析
    SuperSlide之属性targetCell介绍
    了解JSON Web令牌(JWT)
    如何向这些CA来申请数字证书呢?
  • 原文地址:https://www.cnblogs.com/apanda009/p/7295247.html
Copyright © 2011-2022 走看看