房屋染色 -dp

2020-06-04  本文已影响0人  fdsun

这里有n个房子在一列直线上,现在我们需要给房屋染色,分别有红色蓝色和绿色。每个房屋染不同的颜色费用也不同,你需要设计一种染色方案使得相邻的房屋颜色不同,并且费用最小,返回最小的费用。

费用通过一个nx3 的矩阵给出,比如cost[0][0]表示房屋0染红色的费用,cost[1][2]表示房屋1染绿色的费用。

样例
样例 1:

输入: [[14,2,11],[11,14,5],[14,3,10]]
输出: 10
解释: 第一个屋子染蓝色,第二个染绿色,第三个染蓝色,最小花费:2 + 5 + 3 = 10.
样例 2:

输入: [[1,2,3],[1,4,6]]
输出: 3
注意事项
所有费用都是正整数

    /**
     * @param costs: n x 3 cost matrix
     * @return: An integer, the minimum cost to paint all houses
     */
    public static int minCost(int[][] costs) {
        // write your code here
        int n = costs.length;
        if (n == 0) {
            return 0;
        }

        int[][] f = new int[n + 1][3];

        for (int i = 1; i <= n; i++) {
            // color of house i-1 : j
            for (int j = 0; j < 3; j++) {
                f[i][j] = Integer.MAX_VALUE;
                // color of house i-2 : k
                for (int k = 0; k < 3; k++) {
                    if (j != k) {
                        f[i][j] = Math.min(f[i][j], f[i - 1][k] + costs[i - 1][j]);
                    }
                }
            }
        }

        return Math.min(f[n][0], Math.min(f[n][1], f[n][2]));
    }
上一篇 下一篇

猜你喜欢

热点阅读