描述
假设你身上有 n 元,超市里有多种大米可以选择,每种大米都是袋装的,必须整袋购买,给出每种大米的重量,价格以及数量,求最多能买多少公斤的大米
题目链接:https://www.lintcode.com/problem/798/
方法一:递归
#include "iostream"
#include "vector"
#include "cstring"
using namespace std;
int process(vector<int> &prices, vector<int> &weight, vector<int> &amounts, int index, int n) {
if(index < 0 || n < 0){
return 0;
}
int w = 0;
for(int i = 0; i * prices[index] <= n && i <= amounts[index]; i++){
w = max(i * weight[index] + process(prices, weight, amounts, index - 1, n - i * prices[index]),
process(prices, weight, amounts, index - 1, n)
);
}
return w;
}
int main(){
vector<int> prices{3,2};
vector<int> weight{300,160};
vector<int> amounts{1,6};
int n = 8;
cout << process(prices, weight, amounts, prices.size() - 1, n);
}
方法二:dp
class Solution {
public:
/**
* @param n: the money of you
* @param prices: the price of rice[i]
* @param weight: the weight of rice[i]
* @param amounts: the amount of rice[i]
* @return: the maximum weight
*/
int backPackVII(int n, vector<int> &prices, vector<int> &weight, vector<int> &amounts) {
// write your code here
int dp[prices.size()][n + 1];
memset(dp, 0, sizeof(dp));
for(int i = 0; i < prices.size(); i++){
for(int j = 0; j <= n; j++){
for(int k = 0; k * prices[i] <= j && k <= amounts[i]; k++){
dp[i][j] = max(dp[i][j], k * weight[i] + (i - 1 >= 0 ? dp[i - 1][j - k * prices[i]] : 0));
dp[i][j] = max(dp[i][j], i - 1 >= 0 ? dp[i - 1][j] : 0);
}
}
}
return dp[prices.size() - 1][n];
}
};