[Leetcode] 265. Paint House II 解题报告

来源:互联网 发布:淘宝晒图内裤爆光图片 编辑:程序博客网 时间:2024/05/20 22:39

题目

There are a row of n houses, each house can be painted with one of the k colors. 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 k cost matrix. For example, costs[0][0] is the cost of painting house 0 with color 0; costs[1][2] is the cost of painting house 1 with color 2, and so on... Find the minimum cost to paint all houses.

Note:
All costs are positive integers.

Follow up:
Could you solve it in O(nk) runtime?

思路

和《[Leetcode] 256. Paint House 解题报告》的思路一致,只不过这里不是三种颜色,而是k种颜色。我所做到的最优解是时间复杂度为O(n*k),空间复杂度是O(k)。这里动态规划的状态转移方程为:dp[i][j] = min(dp[i - 1].begin(), dp[i - 1].end()) + costs[i][j],并且min中的数不包括dp[j]。

1)空间复杂度的优化:由于dp[i]只和dp中的上一个状态相关,所以可以将空间复杂度从O(n*k)优化到O(k),即我们只记录刷到当前房子时的最优值。

2)时间复杂度的优化:在刷到第i个房子的时候,我们首先花费O(k)的时间找出截止i-1,花费最小和次小的方案,假设是最后一个房子刷成第lowest_index种颜色以及第lower_index种颜色这两种方案。这样在刷第i个房子的时候,如果验证第lowest_index个颜色,那么只需要基于dp[lower_index]这种方案;而验证其它颜色的时候,只需要基于dp[lowest_index]这种方案。

我觉得这应该是可以达到的最优解了。

代码

class Solution {public:    int minCostII(vector<vector<int>>& costs) {        if(costs.size() == 0 || costs[0].size() == 0) {            return 0;         }        int n = costs.size(), k = costs[0].size();          if (k == 1) {            int ret = 0;            for (int i = 0; i < n; ++i) {                ret += costs[i][0];            }            return ret;        }        vector<int> dp(costs[0]);          for(int i = 1; i < n; ++i) {            int lowest_index = 0, lower_index = 1;            if (dp[lower_index] < dp[lowest_index]) {                swap(lowest_index, lower_index);            }            for (int j = 2; j < k; ++j) {                if (dp[j] < dp[lower_index]) {                    lower_index = j;                 }                if (dp[lower_index] < dp[lowest_index]) {                    swap(lowest_index, lower_index);                }            }            int lowest_value = dp[lowest_index], lower_value = dp[lower_index];            for(int j = 0; j < k; ++j) {                 if (j != lowest_index) {                    dp[j] = lowest_value + costs[i][j];                }                 else {                    dp[j] = lower_value + costs[i][j];                }            }        }          return *min_element(dp.begin(), dp.end());      }};

原创粉丝点击