C++ 全排列函数 std::next_permutation与std::prev_permutation
2014-04-14 15:19
501 查看
C++ STL中提供了std::next_permutation与std::prev_permutation可以获取数字或者是字符的全排列,其中std::next_permutation提供升序、std::prev_permutation提供降序。
1.std::next_permutation函数原型
template <class BidirectionalIterator>
bool next_permutation (BidirectionalIterator first, BidirectionalIterator last );
template <class BidirectionalIterator, class Compare>
bool next_permutation (BidirectionalIterator first,BidirectionalIterator last, Compare comp);
说明:next_permutation,重新排列范围内的元素[第一,最后一个)返回按照字典序排列的下一个值较大的组合。
返回值:如果有一个更高的排列,它重新排列元素,并返回true;如果这是不可能的(因为它已经在最大可能的排列),它按升序排列重新元素,并返回false。
2.代码实例
输出:
3.算法实现原理
见:http://hi.baidu.com/bellgrade/item/70b65b8a7ea3c9c398255fd4
算法描述:
1、从尾部开始往前寻找两个相邻的元素
第1个元素i,第2个元素j(从前往后数的),且i<j
2、再从尾往前找第一个大于i的元素k。将i、k对调
3、[j,last)范围的元素置逆(颠倒排列)
1.std::next_permutation函数原型
template <class BidirectionalIterator>
bool next_permutation (BidirectionalIterator first, BidirectionalIterator last );
template <class BidirectionalIterator, class Compare>
bool next_permutation (BidirectionalIterator first,BidirectionalIterator last, Compare comp);
说明:next_permutation,重新排列范围内的元素[第一,最后一个)返回按照字典序排列的下一个值较大的组合。
返回值:如果有一个更高的排列,它重新排列元素,并返回true;如果这是不可能的(因为它已经在最大可能的排列),它按升序排列重新元素,并返回false。
2.代码实例
#include <iostream> #include <algorithm> /// next_permutation, sort using namespace std; int main () { int myints[] = {1,2,3,1}; sort (myints,myints+4); do { cout << myints[0] << ' ' << myints[1] << ' ' << myints[2] << ' '<< myints[3]<<'\n'; } while ( next_permutation(myints,myints+4) ); ///获取下一个较大字典序排列 cout << "After loop: " << myints[0] << ' ' << myints[1] << ' ' << myints[2] << ' '<< myints[3] <<'\n'; return 0; }
输出:
3.算法实现原理
见:http://hi.baidu.com/bellgrade/item/70b65b8a7ea3c9c398255fd4
算法描述:
1、从尾部开始往前寻找两个相邻的元素
第1个元素i,第2个元素j(从前往后数的),且i<j
2、再从尾往前找第一个大于i的元素k。将i、k对调
3、[j,last)范围的元素置逆(颠倒排列)
相关文章推荐
- C++ 全排列函数 std::next_permutation与std::prev_permutation
- C++ 全排列函数 std::next_permutation与std::prev_permutation
- 【C++ STL应用与实现】62: 如何使用std::next_permutation
- C++ STL next_permutation() & prev_permutation()函数
- 全排列函数 next_permutation && prev-permutation
- C++ STL next_permutation() prev_permutation(a,a+n)用法。
- C++ 求排列函数 next_permutation, prev_permutation
- 全排列函数——next_permutation() & prev_permutation()
- my_next_permutation in c++
- 【STL源码剖析读书笔记】【第6章】算法之next_permutation和prev_permutation算法
- c++中的 next_permutation的实现
- prev_permutation_cycle与next_permutation_cycle
- next_permutation和prev_permutation函数的用法
- C++STL的next_permutation
- STL源码学习----next_permutation和prev_permutation算法
- Visual C++ Standard Library:next_permutation
- C++STL的next_permutation
- 【STL源码剖析读书笔记】【第6章】算法之next_permutation和prev_permutation算法
- C++写全排列 next_permutation
- 【C++】【LeetCode】31. Next Permutation && 46. Permutations