查找数字的所有排列

时间:2014-04-20 12:54:55

标签: 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;

和方法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);


          }
         }
      }

  }

输出命令似乎更好

CMD_OUTPUT

我怎样才能更有效率地做到更好?

2 个答案:

答案 0 :(得分:2)

您正在获得堆栈溢出,因为Prem会继续永久地调用prem或直到堆栈溢出。您创建了一个无限循环,因为条件“if(finished == false)”永远不会失败。

我不确定你要在这里完成什么,我建议你重新考虑这个问题,如果有必要,可以在互联网上搜索正确的算法。

答案 1 :(得分:0)

您可以尝试使用Switch/Case代替所有if语句,这可能更有效,但由于您没有很多if/else语句,因此差异无关紧要,在这些陈述的更大范围内,我建议使用Switch/Case或者查找表或哈希列表。

相关问题