【问题标题】:permutation computing in c++C++中的置换计算
【发布时间】:2011-09-29 09:41:54
【问题描述】:

我想编写一个程序,它获取一个整数 n 并打印 1,2,...,n 的所有排列。 我知道有一种递归方式可以做到这一点,而且我知道函数调用的开销。 有没有什么办法不用递归来做到这一点??

【问题讨论】:

  • 如果你计算一些东西并打印即时结果,你永远不需要担心开销:打印本身很慢,当结果更多时你不想这样做比说,1000 行。但对于如此无害的数据量,性能根本不重要。
  • @leftaroundabout:不仅仅是性能开销。问题可能在于输入非常大,在具有小堆栈的系统上会有太多递归
  • @sehe:好的,我应该让这个声明不那么笼统。 在这种特定情况下,堆栈大小无关紧要,因为排列的递归计算(假设通常的算法)在时间上是 O(n!),但在递归深度上只有 O(n)。因此,如果您将n 设为非常大(大到足以成为堆栈问题),那么程序将永远无法完成。

标签: c++ recursion permutation


【解决方案1】:

是的,您可以使用来自<algorithm>std::next_permutation 作为while 条件进行迭代,或者根据您设置循环的方式,这可能是do...while 更合适的场合之一。

【讨论】:

    【解决方案2】:
    #include <vector>
    #include <algorithm>
    
    std::vector<int> v = { 1,2,3,4,5,6,7,8,9,10 }; // see std::iota also
    
    
    // important: sort v if not sorted
    std::sort(v.begin(), v.end());
    
    while (std::next_permutation(v.begin(), v.end()))
    {
          // use v (unique permutation)
    }
    // use v: first sorted position
    

    【讨论】:

      猜你喜欢
      • 2016-02-01
      • 2021-07-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多