【问题标题】:Finding all permutations of a number查找数字的所有排列
【发布时间】: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);


          }
         }
      }

  }

命令的输出似乎更好

我怎样才能更有效、更好地做到这一点?

【问题讨论】:

  • 每当有人将变量与truefalse 进行比较时,都会有一只小猫在某处死去。这是if( ! finished),简单明了。顺便说一句,它是 Permutations,而不是 Premutations。

标签: c# recursion permutation backtracking


【解决方案1】:

您将遇到堆栈溢出,因为 prem 会继续永远调用 prem 或直到堆栈溢出。您已经创建了一个无限循环,因为条件“if (finished == false)”永远不会失败。

我不确定您要在这里完成什么,我建议您重新考虑问题,并在必要时在互联网上搜索正确的算法。

【讨论】:

    【解决方案2】:

    好吧,您可以尝试使用Switch/Case 而不是所有if 语句,这可能更有效,但是由于您没有很多if/else 语句,因此差异并不重要,在更大的范围内我建议使用Switch/Case 或者查找表或哈希列表。

    【讨论】:

      猜你喜欢
      • 2015-06-15
      • 1970-01-01
      • 2015-06-18
      • 2015-12-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-19
      • 1970-01-01
      相关资源
      最近更新 更多