798 - 背包问题VII - LintCode

本文探讨了如何使用递归和动态规划的方法解决一个实际问题:给定有限的资金和超市中各种大米的价格、重量和库存,计算能购买的最大大米总重量。通过实例代码展示了两种策略的实现及其在求解背包问题上的应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

描述
假设你身上有 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];
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值