您的位置:首页 > 大数据 > 人工智能

LeetCode "Paint House II"

2015-08-23 12:21 453 查看
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 :)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: