C++ STL 下一个组合排列
C++ STL Next Permutation with Combination
我知道我可以在包含元素的容器上使用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
数组的词典顺序,元素介于 1
和 n
之间。给定任何这样的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
- 比较并显示使用最小值(a,b)和最大值(a、b)升序排列的4个数字
- 为什么不;名字在地图上是按顺序排列的吗
- 如何在OMNET++中指定与命令行参数组合的输出文件名
- 可组合的lambda/std::函数与std::可选
- C++优先级队列,按对象的唯一指针的特定方法升序排列
- 如何将两个不同矢量的同一位置的两个元素组合在一起
- 按对象的特定方法按升序排列的C++优先级队列
- 混合组合和继承的C++问题
- 我需要将多个函数组合为一个函数
- 构建可组合有向图(扫描仪生成器的汤普森构造算法)
- 通过组合不同的类型来创建唯一的id
- 在C++中寻找排列和组合
- 在 c 中给定一个固定数的情况下,找到所有可能的加法和组合(给定一个总和,找到它的可能的加法和排列
- 从给定字符串中查找长度 k 的所有排列/组合
- 从左到右打印字符串的组合(不是排列)c++
- 排列和组合生成算法
- C++ STL 下一个组合排列
- 查找所有可能的排列或具有相同顺序的组合
- 给定数字的排列和组合
- 生成0,1,…中所有可能的组合n-1, n (k)每个组合应按升序排列