尝试排列时每次递归都会重置列表
List reset on every recursion when attempting to permute
我正在尝试生成列表的所有排列,但每次我递归传入的列表都会重置回其原始状态,这是怎么回事?
public static void PermuteAndSolve(List<City> cities, int recursionLevel, int Length)
{
if (recursionLevel == Length)
{
foreach (City city in cities)
{
Console.Write(city.name);
}
Console.WriteLine("");
}
else
{
for (int i = recursionLevel; i <= Length; i++)
{
swap(cities, recursionLevel, Length);
PermuteAndSolve(cities, recursionLevel + 1, Length);
swap(cities, recursionLevel, Length);
}
}
}
我知道交换工作正常。
我不假装完全理解这段代码在做什么,但你肯定可以在没有令人费解的递归的情况下实现你想要做的事情?像这样的东西(注意:未经测试):
public static void PermuteAndSolve(List<City> cities, int Length)
{
int recursionLevel = 0;
while(recursionLevel < Length)
{
for (int i = recursionLevel; i <= Length; i++) {
swap(cities, recursionLevel, Length);
}
recursionLevel++;
}
foreach(City city in cities)
{
Console.Write(city.name);
}
Console.WriteLine("");
}
可能不正确,但希望你明白我的意思。
原来我是个白痴,我不小心在递归后添加了额外的交换。
实际代码应为:
public static void PermuteAndSolve(List<City> cities, int recursionLevel, int Length)
{
if (recursionLevel == Length)
{
foreach (City city in cities)
{
Console.Write(city.name);
}
Console.WriteLine("");
}
else
{
for (int i = recursionLevel; i <= Length; i++)
{
swap(cities, recursionLevel, Length);
PermuteAndSolve(cities, recursionLevel + 1, Length);
}
}
}
我正在尝试生成列表的所有排列,但每次我递归传入的列表都会重置回其原始状态,这是怎么回事?
public static void PermuteAndSolve(List<City> cities, int recursionLevel, int Length)
{
if (recursionLevel == Length)
{
foreach (City city in cities)
{
Console.Write(city.name);
}
Console.WriteLine("");
}
else
{
for (int i = recursionLevel; i <= Length; i++)
{
swap(cities, recursionLevel, Length);
PermuteAndSolve(cities, recursionLevel + 1, Length);
swap(cities, recursionLevel, Length);
}
}
}
我知道交换工作正常。
我不假装完全理解这段代码在做什么,但你肯定可以在没有令人费解的递归的情况下实现你想要做的事情?像这样的东西(注意:未经测试):
public static void PermuteAndSolve(List<City> cities, int Length)
{
int recursionLevel = 0;
while(recursionLevel < Length)
{
for (int i = recursionLevel; i <= Length; i++) {
swap(cities, recursionLevel, Length);
}
recursionLevel++;
}
foreach(City city in cities)
{
Console.Write(city.name);
}
Console.WriteLine("");
}
可能不正确,但希望你明白我的意思。
原来我是个白痴,我不小心在递归后添加了额外的交换。 实际代码应为:
public static void PermuteAndSolve(List<City> cities, int recursionLevel, int Length)
{
if (recursionLevel == Length)
{
foreach (City city in cities)
{
Console.Write(city.name);
}
Console.WriteLine("");
}
else
{
for (int i = recursionLevel; i <= Length; i++)
{
swap(cities, recursionLevel, Length);
PermuteAndSolve(cities, recursionLevel + 1, Length);
}
}
}