Paint House

来源:互联网 发布:jquery能储存数据不 编辑:程序博客网 时间:2024/05/29 18:25

There are a row of n houses, each house can be painted with one of the three colors: red, blue or 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.

The cost of painting each house with a certain color is represented by a n x 3 cost matrix. For example, costs[0][0] is the cost of painting house 0 with color red; costs[1][2] is the cost of painting house 1 with color green, and so on... Find the minimum cost to paint all houses.

之前自己想出来的题,应该挺好想的,如果相邻颜色不相同,那么后面的颜色的cost只能从前一个的另外两个颜色推过来,所以依赖子问题,而且全局的最优解包含子问题的最优解。就应该用动态规划来做

代码:

public int minCost(int[][] costs) {        // Write your code here        if(costs == null || costs.length == 0 || costs[0].length == 0){            return 0;        }        int n = costs.length;        //直接在原数组上修改不用耗费额外空间        for(int i = 1; i < n; i++){            costs[i][0] = costs[i][0] + Math.min(costs[i - 1][1], costs[i - 1][2]);            costs[i][1] = costs[i][1] + Math.min(costs[i - 1][0], costs[i - 1][2]);            costs[i][2] = costs[i][2] + Math.min(costs[i - 1][0], costs[i - 1][1]);        }        return Math.min(costs[n - 1][0], Math.min(costs[n - 1][1], costs[n - 1][2]));    }


0 0