如何显示KnapSack问题中所有包含的数字?

How to display all included numbers in KnapSack problem?

我在显示已用号码时遇到问题。我正在使用 KnapSack 算法,我想显示我用来获得最高值的所有数字。所以有我的代码:

static int max(int a, int b)
{
    int c = (a > b) ? a : b;
    Console.WriteLine(c);
    return (a > b) ? a : b;
}

// Returns the maximum value that can 
// be put in a knapsack of capacity W            
int knapSack(int[] r, int[] wt, int n, int W)
{

    if (W < 0)
        return Int32.MinValue;
    if (n < 0 || W == 0)
        return 0;
    int include = r[n] + knapSack(r, wt, n, W - wt[n]);
    int exclude = knapSack(r, wt, n - 1, W);
    int V = max(include, exclude);
    return V;
}

使用:

int[] r = new int[] { 3, 4, 8, 5, 6 };
int[] wt = new int[] { 2, 2, 3, 4, 7 };
int W = 11;
int z = W;
int n1 = r.Length;
stopwatch.Start();
int keik = knapSack(r, wt, n1 - 1, W);
stopwatch.Stop();

答案是 28,但我需要显示其中包含的所有 r 个数字。我知道这个数组使用的数字是 8 8 8 和 4,所以我需要以某种方式获取这些数字并显示到控制台。

您可以尝试让函数 return 列出已用物品的方法。 您可以 return 项目值本身,或值的索引,具体取决于您的需要。我在这个例子中使用了这些值。

这是一个实现:

static int knapSack(int[] r, int[] wt, int n, int W, out List<int> list)
{
    if (W < 0) {
        list = new List<int>();
        return Int32.MinValue;
    }
    if (n < 0 || W == 0) {
        list = new List<int>();
        return 0;
    }
    int include = r[n] + knapSack(r, wt, n, W - wt[n], out List<int> includedList);
    int exclude = knapSack(r, wt, n - 1, W, out List<int> excludedList);
    if (include > exclude) {
        includedList.Add(r[n]);
        list = includedList;
        return include;
    } else {
        list = excludedList;
        return exclude;
    }
}

这样调用:

int keik = knapSack(r, wt, n1 - 1, W, out List<int> list);
Console.WriteLine(string.Join(",", list));

输出:

4,8,8,8