Classic DP! For house[i] to pick a min-color from dp[i-1], we only need to check if color j is the min cost color index of dp[i - 1]; if yes, then we pick the 2nd smallest min cost color. Also: we can optimize memory complexity by using rolling array.
class Solution { public: void getSm1n2(vector<int> &house, int &sm1, int &sm2) { size_t len = house.size(); int curr1 = house[0], curr2 = INT_MAX; sm1 = 0; for (int i = 1; i < len; i++) { int v = house[i]; if (v < curr1) { curr2 = curr1; sm2 = sm1; curr1 = v; sm1 = i; } else { if (v < curr2) { curr2 = v; sm2 = i; } } } } int minCostII(vector<vector<int>>& costs) { int ret = 0; unsigned nHouseCnt = costs.size(); if (nHouseCnt == 0) return ret; unsigned nColorCnt = costs[0].size(); // Can be optimized using rolling array vector<vector<int>> dp(nHouseCnt, vector<int>(nColorCnt, 0)); dp[0] = costs[0]; int sm1, sm2; getSm1n2(dp[0], sm1, sm2); for (int i = 1; i < nHouseCnt; i++) { for (int j = 0; j < nColorCnt; j++) { dp[i][j] = dp[i - 1][j == sm1 ? sm2 : sm1] + costs[i][j]; } getSm1n2(dp[i], sm1, sm2); } ret = *std::min_element(dp[nHouseCnt - 1].begin(), dp[nHouseCnt - 1].end()); return ret; } };
And I got 1AC in my onsite interview w\ this problem :)