LeetCode 256. Paint House

来源:互联网 发布:股票模拟练习软件 编辑:程序博客网 时间:2024/04/29 14:18

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.

Note:
All costs are positive integers.

思路:
1. 这代表一类题,遍历所有可能性,且遵循一定的约束条件。最直接的方法是,遍历所有可能性,找出最小cost,但这样的复杂度就是指数增长,o(2^n)。
2. 如何简化复杂度,减少不必要的运算?可以把问题看成是有层次的问题,这样就可以分割成小的问题,小的问题继续分成更小的问题,直到问题不能分割为止。和直接遍历把所有可能性平等的对待相比,这样有层次的方式,是把小问题解决了,大问题的解决就容易了,减少了遍历的可能性!因此,怎么看待或怎么建模这个问题,决定了采用什么方法解决这个问题。
3. 用DP,二维dp。找递推关系,小问题和大问题之间的逻辑联系!
2. 突然有个想法,应该设法总结一下,很多问题用简单粗暴的方法做,复杂度为什么很差?因此,需要借助一些辅助手段来回避这一类问题!

int minCost(vector<vector<int>>& costs) {    int n=costs.size();    vector<vector<int>> dp(n+1,vector<int>(3,0));//写完这一行,意识到是否可以不用新建array,直接在给定的2D array上做这个dp呢?    for(int i=1;i<n;i++){        vector<int> cur=costs[i-1];        for(int j=0;i<3;j++){            dp[i][j]=dp[i][j]+min(cur[(j+1)%3],cur[(j+2)%3]);        }    }    return min(min(costs.back()[0],costs.back()[1]),costs.back()[2]);}
0 0
原创粉丝点击