C# 求一个数的所有置换

C# 求一个数的所有置换,c#,recursion,permutation,backtracking,C#,Recursion,Permutation,Backtracking,我正在用回溯法寻找三个数字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; static void perm(int a, int b, int c) { Console.WriteLine("( {0}, {1}, {2} )", a, b,

我正在用回溯法寻找三个数字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;
  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)

      }

  }
找到(1,2,3)的每个置换的方法perm如下:

  static int a=1;
  static int b=2;
  static int c=3;
  static int aCount;
  static int bCount;
  static int cCount;
  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)

      }

  }
static void perm(inta、intb、intc)
{
Console.WriteLine(({0},{1},{2})”,a,b,c);/(1,2,3)

if(aCount由于prem会一直调用prem,或者直到堆栈溢出为止,所以您得到了堆栈溢出。您创建了一个无限循环,因为条件“if(finished==false)”从未失败


我不确定你想在这里实现什么,我建议你重新思考这个问题,如果有必要,在互联网上搜索正确的算法。

好吧,你可以尝试使用
Switch/Case
而不是所有
if
语句,这可能会更有效,但因为你没有太多
if/else
语句差异其实并不重要,在这些语句的更大范围内,我建议使用
开关/大小写
,或者一个查找表或哈希表。

每次有人将一个变量与
进行比较时,一只小猫就会死在某个地方。如果(!完成)
,简单明了。顺便说一句,这是置换,不是预置换。你可能应该这样做