gpt4 book ai didi

c# - 排列中递归的不一致行为

转载 作者:行者123 更新时间:2023-11-30 23:15:50 25 4
gpt4 key购买 nike

我有一个使用堆排列算法对数组进行排列的类,但是当我打印出所有排列时,我得到了所有正确的排列,将项目添加到列表中,然后打印列表,我重复了相同的项目.这是我的代码

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;
}
}

最佳答案

数组是引用类型!因此,您对同一个对象进行操作,您会更改所有对象中的项目。在将数组添加到列表之前克隆该数组。

permutated_items.Add((T[])array.Clone());

关于c# - 排列中递归的不一致行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42324689/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com