我在显示已用数字时遇到问题。我正在使用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,所以我需要某种方式来获取这些数字并显示在控制台上。
您可以尝试让函数返回已用项目列表的方法。 您可以根据需要返回项目值本身或值的索引。我在此示例中使用了值。
这里是一个实现:
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