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

      

      

  • 相关阅读:
    013.Kubernetes认证授权
    012.Kubernetes的configmap和secret配置
    011.Kubernetes使用共享存储持久化数据
    010.kubernets的调度系统之daemonset
    009.kubernets的调度系统之污点和容忍
    008.kubernets的调度系统之标签选择器
    007.kubernets的headless service配置和ingress的简单配置
    Meterpreter初探
    渗透第一课:尝试渗透
    Metasploit漏洞扫描
  • 原文地址:https://www.cnblogs.com/apanda009/p/7295247.html
Copyright © 2011-2022 走看看