【发布时间】:2014-04-20 12:54:55
【问题描述】:
我正在努力使用回溯查找三个数字 1、2、3 的所有排列
我将 a,b,c 定义如下:
static int a=1;
static int b=2;
static int c=3;
static int aCount;
static int bCount;
static int cCount;
和 perm 方法,它找到 (1,2,3) 的每个排列,如下所示:
static void perm(int a, int b, int c)
{
Console.WriteLine("( {0}, {1}, {2} )", a, b, c); // (1,2,3 )
if (aCount<2)
{
aCount++;
// perm(a, b, c); no need for this one..It's already done above ^
perm(a,c,b); // (1,3,2 )
}
else if(bCount<2)
{
bCount++;
perm(b,a,c); //(2,1,3)
perm(b,c,a); //(2,3,1)
}
else if(cCount<2)
{
cCount++;
perm(c,b,a); //(3,2,1)
perm(c,a,b); //(3,1,2)
}
}
它有效,但结果并不令人满意。 (代码肯定有逻辑问题)。
例如,有很多重复项,我的代码没有比这一步更好的了。
是否有其他方法(例如添加或减去 a,b,c )可以治愈我的代码?
Gig 是代码中只接受递归回溯(因此我遇到了困难)。
感谢转发人员的帮助。
更新:
我已经更新了代码,试图修复我能做的,并让它工作,减少错误输出:
static void perm(int a, int b, int c)
{
Console.WriteLine("( {0}, {1}, {2} )", a, b, c); // (1,2,3 )
if (aCount < 2)
{
aCount++;
// Console.WriteLine("( {0}, {1}, {2} )", a, b, c); // (1,2,3 )
// perm(a, b, c);
perm(a, c, b);
if (bCount < 2)
{
bCount++;
perm(b, a, c);
perm(b, c, a);
if (cCount < 2)
{
cCount++;
perm(c, b, a);
perm(c, a, b);
}
}
}
}
命令的输出似乎更好
我怎样才能更有效、更好地做到这一点?
【问题讨论】:
-
每当有人将变量与
true或false进行比较时,都会有一只小猫在某处死去。这是if( ! finished),简单明了。顺便说一句,它是 Permutations,而不是 Premutations。
标签: c# recursion permutation backtracking