向列表添加值会更改上一个列表中的元素
本文关键字:列表 上一个 元素 添加 | 更新日期: 2023-09-27 18:29:41
我正在尝试实现某个算法,它应该使用sth,什么是四维的
但我在向新列表添加元素时遇到了问题:当我向列表添加新值时:temp2,其他列表中以前的值正在更改
有人能告诉我哪里做错了什么吗?
示例:
对于n=4,k=2:
当i=3,j=1
->tab[3,1]=[{1},{2},{3}](应该总是这样)
则当i=3时,j=2 tab[3,1]正在更改:
->选项卡[3,1]:[{1,3},{2,3}和{3}]
则当i=4,j=1
->tab[4,1]=[{1,3},{2,3}、{3}、{4}]
则当i=4时,j=2选项卡[4,1]正在更改:
->选项卡[4,1]:[{1,3,4}、{2,3,4}、{3,4}和{4}]
程序中我的算法代码
while (true)
{
int n = int.Parse(Console.ReadLine());
int k = int.Parse(Console.ReadLine());
List<List<int>>[,] tab = new List<List<int>>[n + 1, k + 1];
for (int i = 1; i <= n; i++)
{
int j = 0;
while (j <= i && j <= k)
{
tab[i, j] = new List<List<int>>();
List<int> toAdd = new List<int>();
if (j == 0)
{
toAdd.Clear(); //add empty
tab[i, 0].Add(toAdd);
}
else if (i == j)
{
for (int p = 1; p <= j; p++)
toAdd.Add(p);
tab[i, i].Add(toAdd);
}
else
{
var temp = new List<List<int>>();
var temp2 = new List<List<int>>();
temp.AddRange(tab[i - 1, j]);
temp2.AddRange(tab[i - 1, j - 1]);
foreach (var x in temp2) //add 'i' as last element for each element of temp2
x.Add(i); //here is sth wrong (bad reference?)
temp2.Reverse(); //reverse order
tab[i, j].AddRange(temp);
tab[i, j].AddRange(temp2);
}
j++;
}
}
//show tab[n,k] in console
}
为什么我使用这样简单的变量——我在类中实现算法,所以我必须使用它们。
调用temp2.AddRange(tab[i - 1, j - 1])
时,将引用复制到[i - 1, j - 1]
的列表中。因此,当您修改temp2
时,您也会修改原始列表(它们是同一个对象)。
您需要为内部列表创建新列表:
temp.AddRange(tab[i - 1, j].Select(l => new List<int>(l)));
temp2.AddRange(tab[i - 1, j - 1]).Select(l => new List<int>(l)));