我正在尝试生成列表的所有排列,但每次我递归列表时,我都会重置回原来的状态,那是什么?
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);
}
}
}
我知道交换工作正常。
答案 0 :(得分:0)
我并没有假装准确理解这段代码的作用,但是如果没有令人费解的递归,你肯定可以实现你想要做的事情吗?这样的事情(注意:未经测试):
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("");
}
可能不正确,但希望你明白我的观点。
答案 1 :(得分:0)
原来我是一个白痴,我在意外递归之后添加了额外的交换。 真实代码应为:
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);
}
}
}