Paint House
自己的写法:
class Solution {
public:
/**
* @param costs: n x 3 cost matrix
* @return: An integer, the minimum cost to paint all houses
*/
int minCost(vector<vector<int> > &costs) {
// write your code here
int length = costs.size();
vector<vector<int> > dp(length + ,vector<int>());
for(int i = ;i < ;i++)
dp[][i] = ;
for(int i = ;i <= length;i++){
dp[i][] = min(dp[i-][] + costs[i-][],dp[i-][] + costs[i-][]);
dp[i][] = min(dp[i-][] + costs[i-][],dp[i-][] + costs[i-][]);
dp[i][] = min(dp[i-][] + costs[i-][],dp[i-][] + costs[i-][]);
}
int min_num = INT_MAX;
for(int i = ;i < ;i++){
min_num = min(min_num,dp[length][i]);
}
return min_num;
}
};
更优的写法:
https://www.cnblogs.com/grandyang/p/5319384.html
class Solution {
public:
int minCost(vector<vector<int>>& costs) {
if (costs.empty() || costs[].empty()) return ;
vector<vector<int>> dp = costs;
for (int i = ; i < dp.size(); ++i) {
dp[i][] += min(dp[i - ][], dp[i - ][]);
dp[i][] += min(dp[i - ][], dp[i - ][]);
dp[i][] += min(dp[i - ][], dp[i - ][]);
}
return min(min(dp.back()[], dp.back()[]), dp.back()[]);
}
};