在C中递归解决背包问题的麻烦

trouble with solving knapsack issue recursively in C

我需要通过递归、记忆和动态规划来解决背包问题。目前我被困在递归方法中。

问题是我实际上不确定我的代码是否按预期执行(而且我也不确定如何检查)。我根据我在互联网上其他地方找到的代码改编了代码。

问题涉及利润和质量。每个项目都有一个利润和质量相关联,有 MAX_N(数量)可用项目和 MAX_CAPACITY 质量。目的是背包里尽可能多"profit"

完整代码如下:

#include <stdio.h>
#include <stdlib.h>

#define MAX(x, y) (((x) > (y)) ? (x) : (y))
#define MIN(x, y) (((x) < (y)) ? (x) : (y))

#define MAX_N 10
#define MAX_CAPACITY 165

int m[MAX_N][MAX_CAPACITY];

int knapsackRecursive(int capacity, int mass[], int profit[], int n) {
    if (n < 0)
        return 0;
    if (profit[n] > capacity)
        return knapsackRecursive(capacity, mass, profit, n-1);
    else
        return MAX(knapsackRecursive(capacity, mass, profit, n-1), knapsackRecursive(capacity - mass[n], mass, profit, n-1) + profit[n]);
}

int knapsackMemoized(int capacity, int mass[], int profit[], int n) {

}

int knapsackDynamic(int capacity, int mass[], int profit[], int n) {

}

void test() {

    int M1[4] = {6, 3, 2, 4};
    int P1[4] = {50, 60, 40, 20};

    int M2[10] = {23, 31, 29, 44, 53, 38, 63, 85, 89, 82};
    int P2[10] = {92, 57, 49, 68, 60, 43, 67, 84, 87, 72};

    // a)
    knapsackRecursive(MAX_CAPACITY, M1, P1, MAX_N);
    knapsackRecursive(MAX_CAPACITY, M2, P2, MAX_N);

    // b)
    knapsackMemoized(MAX_CAPACITY, M1, P1, MAX_N);
    knapsackMemoized(MAX_CAPACITY, M2, P2, MAX_N);

    // c)
    knapsackDynamic(MAX_CAPACITY, M1, P1, MAX_N);
    knapsackDynamic(MAX_CAPACITY, M2, P2, MAX_N);

}

int main() {
    test();
}

正如我所提到的,我实际上不确定首先要如何检查计算是否正确(例如,在何处插入调试 printf())。我尝试打印 M1 / P1 的最终结果,结果是“170”,我认为这是不正确的。

编辑:这是练习提供的示例:

Example: Given a knapsack of capacity 5, and items with mass[] = {2, 4, 3, 2} and profit profit[] = {45, 40, 25, 15}, the best combination would be item 0 (with mass 2 and profit 45) and item 2 (with mass 3 and with profit 25) for a total profit of 70. No other combination with mass 5 or less has a greater profit.

程序有误,请看这一行:

if (profit[n] > capacity)
    return knapsackRecursive(capacity, mass, profit, n-1);

这里你比较利润和产能。您应该与 mass[n] 进行比较。其余代码目前看起来没问题。

也许你最好使用库的最大值而不是 "ternary operator",因为这样的运算符会创建分支,而有时最大值可以在没有分支的情况下完成。

您可以尝试解决的程序问题至少是生成包并打印它。您还可以使用已知解决方案的背包问题实例。