C# 置换中递归的不一致行为
我有一个类,它使用堆置换算法对数组进行置换,但是当我打印出所有置换时,我得到了所有正确的置换,将项目添加到列表中,然后打印列表,我得到了重复的相同项目。这是我的密码C# 置换中递归的不一致行为,c#,recursion,C#,Recursion,我有一个类,它使用堆置换算法对数组进行置换,但是当我打印出所有置换时,我得到了所有正确的置换,将项目添加到列表中,然后打印列表,我得到了重复的相同项目。这是我的密码 using System; using System.Collections.Generic; namespace HeapsPermutation { class Program { static void Main(string[] args) { string[] numbers
using System;
using System.Collections.Generic;
namespace HeapsPermutation
{
class Program
{
static void Main(string[] args)
{
string[] numbers = new string[4];
numbers[0] = "a";
numbers[1] = "b";
numbers[2] = "c";
numbers[3] = "d";
Permutation<string>.permutate(numbers.Length, numbers);
Console.Read();
}
}
class Permutation<T>
{
static List<T[]> permutated_items = new List<T[]>();
public static void permutate(int n, params T[] array)
{
if (n == 1)
{
foreach (T x in array)
{
Console.Write(x); // gives correct result
}
Console.WriteLine();
permutated_items.Add(array); // does no add correct result
}
else
{
for (int i = 0; i < n - 1; i++)
{
permutate(n - 1, array);
if (n % 2 == 0)
{
swap(ref array[i], ref array[n - 1]);
}
else
{
swap(ref array[0], ref array[n - 1]);
}
}
permutate(n - 1, array);
}
}
private static void swap(ref T x, ref T y)
{
T temp = x;
x = y;
y = temp;
}
}
使用系统;
使用System.Collections.Generic;
命名空间堆术语置换
{
班级计划
{
静态void Main(字符串[]参数)
{
字符串[]数字=新字符串[4];
数字[0]=“a”;
数字[1]=“b”;
数字[2]=“c”;
数字[3]=“d”;
置换。置换(数字。长度,数字);
Console.Read();
}
}
类置换
{
静态列表置换的_项=新列表();
公共静态void置换(int n,参数T[]数组)
{
如果(n==1)
{
foreach(数组中的tx)
{
Console.Write(x);//给出正确的结果
}
Console.WriteLine();
置换的_items.Add(array);//不添加正确的结果
}
其他的
{
对于(int i=0;i
}数组是引用类型!因此,您对同一对象进行操作,并更改所有对象中的项。克隆阵列,然后再将其添加到列表中
permutated_items.Add((T[])array.Clone());
你能提供一份报告吗?我希望能够复制粘贴并在控制台应用程序中运行您的代码,并查看您面临的问题代码>(修复编译问题)并使用您提供的参数执行,它将正确打印置换。@Enigmativity我刚刚添加了一个最小、完整且可验证的参数example@Paweukasik是的,它打印出了所有的排列,但我想把它添加到列表中