【发布时间】:2019-08-01 06:46:58
【问题描述】:
我无法理解有关递归和数组的内容。
基本上,该程序所做的是检查可以放置在两个盒子中的物品的最大重量是多少。我知道它远非现在的完美,但这不是重点。
通常一切正常,但是,现在我决定在重量最大时查看每个盒子的内容。为此,我尝试使用 arr1 和 arr2。
我不明白为什么 arr1 和 arr2 得到不同的结果(第一个选项给了我想要的结果,第二个没有)。
这是程序:
#define N 5
int help(int items[N][2], int box1[N], int box2[N], int rules[N][N],
int optimal,int current_weight,int item,int arr1[],int arr2[])
{
if (item == N)
{
if(current_weight>optimal) //This is the first option
{
memcpy(arr1,box1,sizeof(int)*N);
memcpy(arr2,box2,sizeof(int)*N);
}
return current_weight;
}
int k = items[item][1]; int sol;
for (int i = 0; i <= k; i++)
{
for (int j = 0; i+j <= k; j++)
{
box1[item] += i; box2[item] += j;
if (islegal(items, box1, box2, rules))
{
sol = help(items, box1, box2, rules, optimal,
current_weight + (i + j)*items[item][0],item+1,arr1,arr2);
if (sol > optimal)
{
optimal = sol;
memcpy(arr1,box1,sizeof(int)*N); //This is the second option
memcpy(arr2,box2,sizeof(int)*N);
}
}
box1[item] -= i; box2[item] -= j;
}
}
return optimal;
}
int insert(int items[N][2], int rules[N][N])
{
int box1[N] = { 0 }; int arr1[N] = { 0 };
int box2[N] = { 0 }; int arr2[N] = { 0 };
int optimal = 0;
int x = help(items, box1, box2, rules,0, 0,0,arr1,arr2);
print(arr1, N);
print(arr2, N);
return x;
}
谁能解释造成这种差异的原因?为什么第一个选项正确而第二个选项不正确?我自己也想不通。
非常感谢。
【问题讨论】:
标签: c arrays recursion backtracking