- Backpack X
You have a total of n yuan. Merchant has three merchandises and their prices are 150 yuan, 250 yuan and 350 yuan. And the number of these merchandises can be considered as infinite. After the purchase of goods need to be the remaining money to the businessman as a tip, finding the minimum tip for the merchant.
Example
Example 1:
Input: n = 900
Output: 0
Example 2:
Input: n = 800
Output: 0
经典的完全背包例题。
解法1:最朴素的2维数组
注意:
-
完全背包和01背包的区别就是转移方程里面,
f[i][w] = max{f[i-1][w], f[i-1][w-Ai-1] + Vi-1 | w≥Ai-1 且f[i-1][w-Ai-1] ≠-1} //01背包
f[i][w] = max{f[i-1][w], f[i][w-Ai-1] + Vi-1} //完全背包
i-1和i的区别。
注意,完全背包这里的转移方程本来应该是f[i][w] = max_k{f[i-1][w-kAi-1] + kVi-1},这里k>=0表示w里面最多能去取多少Ai-1。
那为什么该方程等价于
f[i][w] = max{f[i-1][w], f[i][w-Ai-1] + Vi-1}
呢?
我们举个例子,假如Ai-1=2, Vi-1=V
f[i][10]=max{f[i-1][10]+0V, f[i-1][8]+1V, f[i-1][6]+2V, f[i-1][4]+3V, f[i-1][2]+4V, f[i-1][0]+5V}
而
f[i][8]=max{f[i-1][8]+0V, f[i-1][6]+2V, f[i-1][4]+3V, f[i-1][5]+4V}
可得
f[i][10]=max{f[i-1][10], f[i][8]+V}
即f[i][w] = max{f[i-1][w], f[i][w-Ai-1]+V} -
完全背包和01背包都只需要2重循环,优化也只是空间优化而已。
多重背包需要3重循环(不管优不优化),优化也只是空间优化。 -
j=0和j=1开始都可以。
-
i和j两层循环顺序可互换。
class Solution {
public:
/**
* @param n: the money you have
* @return: the minimum money you have to give
*/
int backPackX(int n) {
vector<int> prices={150, 250, 350};
vector<vector<int>> dp(4, vector<int>(n + 1));
for (int i = 1; i <= 3; ++i) {
for (int j = 0; j <= n; ++j) { //j=1 也可以
dp[i][j] = dp[i - 1][j];
if (j >= prices[i - 1]) { //note it is >=
dp[i][j] = max(dp[i - 1][j], dp[i][j - prices[i - 1]] + prices[i - 1]);
}
}
}
return n - dp[3][n];
}
};
解法2:
空间优化后2层循环,一重数组。
注意:
- 01背包空间优化内循环反序,完全背包空间优化内循环正序。
class Solution {
public:
/**
* @param n: the money you have
* @return: the minimum money you have to give
*/
int backPackX(int n) {
vector<int> dp(n + 1, 0);
//dp[x] means the maximum amount (that is less than x) used to buy the mechandises
vector<int> prices = {150, 250, 350};
for (int i = 0; i < 3; ++i) {
for (int j = prices[i]; j <= n; ++j) {
dp[j] = max(dp[j], dp[j - prices[i]] + prices[i]);
}
}
return n - dp[n];
}
};
代码同步在
https://github.com/luqian2017/Algorithm