背包问题递归函数的意外结果

时间:2019-04-10 14:39:23

标签: c

我必须编写一个简单的程序来解决背包问题。 我现在编写了这段代码,我认为这就是我所需要的,但是每次执行它都会得到不同的结果。我所能想到的是存在内存分配问题,但我不知道如何解决。有什么想法吗?

P.S。也许这是一个愚蠢的问题,但我从未在C语言中工作过。

#include <stdio.h>

int max(int a, int b){
  if(a > b) {
    return a;
  } else {
    return b;
  }
}

int knapsack(int prices[], int weight[], int n, int max_weight){
  if(n < 0)
    return 0;
  if (weight[n] > max_weight)
    return knapsack(prices, weight, n-1, max_weight);
  else
    return max(knapsack(prices, weight, n-1, max_weight), (knapsack(prices, weight, n-1, max_weight - weight[n]) + prices[n]));
}

int main(int argc, char const *argv[]) {
  int i, weight[] = {2,3,3,4}, prices[] = {1,5,2,9}, max_weight = 7, n, result;
  for (i=0; i<argc; i++) {
    printf("%d: \"%s\"\n", i, argv[i]);
  }
  n = (sizeof(weight))/(sizeof(weight[0]));
  result = knapsack(prices, weight, n, max_weight);
  printf("%d\n", result);
  return 0;
}

结果 enter image description here

1 个答案:

答案 0 :(得分:2)

看起来您正在使用太大的数字索引数组。 你得到数组的大小

n = (sizeof(weight))/(sizeof(weight[0]));

您无法为n的权重编制索引,因为它的索引只有0n-1

尝试致电

result = knapsack(prices, weight, n-1, max_weight);
相关问题