C++ STL 下一个组合排列

C++ STL Next Permutation with Combination

本文关键字:排列 组合 下一个 STL C++      更新时间:2023-10-16

我知道我可以在包含元素的容器上使用std::next_permutation [1, 2, 3]这些元素将生成该序列的 6 种排列。我想做的是给出一些集合[1, 2, 3, 4, 5, 6]生成大小为 3 的所有可能排列。因此,对于此示例,[4, 3, 2]将是此标准产生的排列之一。我正在寻找一种 STL 方法来做到这一点(如果可能的话(,而不是编写我自己的组合函数。我应该阅读任何特定的 STL 实现?

目前(截至2016年(没有单一的STD函数可以做到这一点。您最接近的是来自 http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2008/n2639.pdf 的提案

您想要的函数称为next_partial_permutation,如下所示(来自 N2639(:

template  <class  BidirectionalIterator >
bool next_partial_permutation(
  BidirectionalIterator  first ,
  BidirectionalIterator  middle ,
  BidirectionalIterator  last)
{
  std::reverse(middle , last);
  return std::next_permutation(first , last);
}

这不是最有效的算法,但它很容易。您必须从排序的元素开始。要获得下一个 k 排列,请反转最后的 n-k 个元素,然后尝试获取下一个排列。前 k 个元素是下一个 k 排列。

这是一个用Smalltalk编写的算法。

该算法的思想是考虑长度m数组的词典顺序,元素介于 1n 之间。给定任何这样的array,该方法next用它的下一个部分排列替换array

我创建了一个包含三个实例变量的类

array       the current permutation of length m
m           the size of array
complement  the SortedCollection of integers not in array

实例创建方法m:n:工作原理如下

m: length n: limit
  m := length.
  array := (1 to: m) asArray.
  complement := (m + 1 to: limit) asSortedCollection

在此类中,该方法next修改array,以便它现在将保存下一个排列。

值得一提的是,该算法不是递归的。

该方法next iff nil iff 的答案array包含顺序中的最后一个排列(即 array = (n, n-1, ...., n-m+1) .

要计算所有排列,请从array = (1 ... m)开始并发送next,直到答案nil

next
  | index max h a c |
  index := self lastDecreasingIndex.
  max := complement max.
  h := (index to: m) findLast: [:i | (array at: i) < max] ifAbsent: nil.
  h isNil
    ifTrue: [
      index = 1 ifTrue: [^nil].
      a := array at: index - 1.
      index to: m do: [:i | complement add: (array at: i)].
      c := complement detect: [:cj | a < cj].
      array at: index - 1 put: c.
      complement remove: c; add: a.
      index to: m do: [:i | array at: i put: complement removeFirst]]
    ifFalse: [
      h := h + index - 1.
      a := array at: h.
      c := complement detect: [:ci | a < ci].
      array at: h put: c.
      complement remove: c; add: a.
      h + 1 to: m do: [:i | complement add: (array at: i)].
      h + 1 to: m do: [:i | array at: i put: complement removeFirst]]

哪里

lastDecreasingIndex
  | index |
  index := m.
  [(array at: index - 1) > (array at: index)] whileTrue: [
    index := index - 1.
    index = 1 ifTrue: [^1]].
  ^index