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.
And I got 1AC in my onsite interview w\ this problem :)
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 :)
相关文章推荐
- [leetcode-172]Factorial Trailing Zeroes (c)
- windows中vim-airline研究笔记
- Bad Hair Day(问题抽象转化+“贡献值”思想+单调栈)
- surf算法生成动态链接库使用出现crtstuff.c:(.text+0x5510): multiple definition of `main'
- Hdu 2015 Multi-University Training Contest10
- Codeforces Round #317 [AimFund Thanks-Round] (Div. 2) B. Order Book
- 作用域链(Scope Chain)
- [LeetCode]Climbing Stairs
- go get报错 error: RPC failed; result=56, HTTP code =
- Aizu - 2564 Tree Reconstruction 并查集
- POJ2010--Moo University-Financial Aid(二分)
- JPA的PAI测试
- Aizu - 2555 Everlasting Zero 模拟
- hdoj 1022 Train problem 1【栈 的理解】
- 调用Process.waitfor导致的进程挂起
- sleep() wait() yeild()三者之间的区别?
- hdu 1239 Calling Extraterrestrial Intelligence Again
- Debug Assertion Failed! File: afx.inl
- PAT 1014. Waiting in Line (30)
- unresolved external symbol _winmain@16