题解
动态规划,Easy级别。
动态规划题,重点是找到传递公式,思路见注释。
class Solution {
public:
int minCost(vector<vector<int>>& costs) {
if(costs.empty()) return 0;
int n = costs.size(), m = costs[0].size();
// dp[i][j]: The min cost with the current house painted color j
vector<vector<int>> dp(n, vector<int>(m));
dp[0] = costs[0];
// dp[i][j] = costs[i][j] + min(dp[i-1][not j])
for(int i = 1; i < n; i++) {
dp[i][0] = costs[i][0] + min(dp[i-1][1], dp[i-1][2]);
dp[i][1] = costs[i][1] + min(dp[i-1][0], dp[i-1][2]);
dp[i][2] = costs[i][2] + min(dp[i-1][0], dp[i-1][1]);
}
return *min_element(dp[n-1].begin(), dp[n-1].end());
}
};