paint i 和 ii一样,只是限定了k=3,所以可以写的简单一些。
paint ii
https://leetcode.com/problems/paint-house-ii/
未压缩空间:
class Solution {
public:
int minCostII(vector<vector<int>>& costs) {
int n = costs.size();
if(n==0) return 0;
int m = costs[0].size();
vector<vector<int> > dp(n,vector<int>(m,0));
//init
for(int i = 0; i < m; i++)
dp[0][i] = costs[0][i];
//dp
for(int i = 1; i < n; i++) {
for(int j = 0; j < m; j++) {
dp[i][j] = INT_MAX;
for(int k = 0; k < m; k++) {
if(j == k) continue;
dp[i][j] = min(dp[i][j], dp[i-1][k] + costs[i][j]);
}
}
}
int res = INT_MAX;
for(int i = 0; i < m; i++)
res = min(res, dp[n-1][i]);
return res;
}
};
压缩空间是否可行?不能直接压缩,要记录两个min1和min2:
https://leetcode.com/discuss/52982/c-dp-time-o-nk-space-o-k
class Solution {
public:
int minCostII(vector<vector<int>>& costs) {
if (costs.empty()) return 0;
int n = costs.size(), k = costs[0].size(), m1 = 0, m2 = 0;
vector<int> dp(k, 0);
for (int i = 0; i < n; i++) {
int t1 = m1, t2 = m2;
m1 = m2 = INT_MAX;
for (int j = 0; j < k; j++) {
dp[j] = (dp[j] != t1 ? t1 : t2) + costs[i][j];
if (m1 <= dp[j]) m2 = min(m2, dp[j]);
else m2 = m1, m1 = dp[j];
}
}
return m1;
}
};
Paint Fence
https://leetcode.com/problems/paint-fence/
不能有两个以上相邻的fence是相同color。
第三根柱子要么根第一个柱子不是一个颜色,要么跟第二根柱子不是一个颜色
class Solution {
public:
int numWays(int n, int k) {
if(n==0 ||k==0) return 0;
vector<int> dp(n);
dp[0] = k;
dp[1] = k*k;
for(int i = 2; i < n; i++) {
dp[i] = (k-1)* (dp[i-1] + dp[i-2]);
}
return dp[n-1];
}
};