C++ 求排列函数 next_permutation, prev_permutation
来源:互联网 发布:多益网络在线笔试 编辑:程序博客网 时间:2024/05/18 01:25
今天在POJ上遇到了一个题目,我想的解题思路里面需要求出一个数组中所有的排列情况,自己想了半天,觉得实现很复杂,于是搜索一下,才发现有next_permutation这个方法。
简单的介绍一下,next_permutation能生成下一个字典集更大一点的排列, 而prev_permutation则刚好相反,生成下一个字典集更小一点的排列。
下面是一个示例,里面有一些关于next_permutation()函数的用法示例
#include <iostream>#include <algorithm>using namespace std;void TestCharArray(){ cout << "Test char array:" << endl; char chs[] = {'3','5','4','6'}; int number = sizeof(chs)/sizeof(char); //next_permutation()需要两个参数,参数1:要开始排列的元素的指针, 参数2:要结束排列的元素的指针 //之调用一次,就生成一个比上一个字典序大的排列 next_permutation(chs + 0, chs + number); for(int i = 0; i < number; i++){ cout << chs[i] << "\t"; } cout << endl; //通过这种方式一直调用,当字典序达到最大,也就是减序的时候,next_permutation()返回false do{ for(int i = 0; i < number; i++){ cout << chs[i] << "\t"; } cout << endl; }while(next_permutation(chs + 0, chs + number));//注意这里有个分号 }void TestIntArray(){ cout << "test int array:"<< endl; int a[] = {1, 2, 3, 4}; int number = sizeof(a) / sizeof(int); do{ for(int i = 0; i < number; i++){ cout << a[i] << "\t"; } cout << endl; }while(next_permutation(a, a + number));}void TestString(){ cout << "test string:" << endl; string s = "abcd"; do{ cout << s << endl; }while(next_permutation(s.begin(), s.end()));} int main(){ TestCharArray(); TestString(); TestIntArray();}
ps: 如果next_permutation函数生成的字典集不是最大的,它就会返回true,所以上面的循环才能一直进行下去,直到排列成字典集最大的情况,然后返回false。
0 0
- C++ 求排列函数 next_permutation, prev_permutation
- 全排列函数next_permutation,prev_permutation
- 排列函数 prev_permutation和next_permutation的使用
- 全排列函数 : next_permutation and prev_permutation
- 全排列函数next_permutation与prev_permutation
- 全排列函数——next_permutation() & prev_permutation()
- C++ 全排列函数 std::next_permutation与std::prev_permutation
- STL全排列函数 next_permutation prev_permutation 及拓展
- stl全排列next_permutation()与prev_permutation()函数用法
- next_permutation函数和prev_permutation函数
- STL/next_permutation()和prev_permutation()函数
- STL之生成全排列:next_permutation & prev_permutation
- STL全排列算法next_permutation和prev_permutation
- C++标准库---排列元素next_permutation()&prev_permutation()
- STL_算法_排列(prev_permutation、next_permutation)
- next_permutation & prev_permutation
- next_permutation,prev_permutation
- next_permutation & prev_permutation
- 多级指针运算
- 进程的有哪几种状态,状态转换图,及导致转换的事件
- HDU 4607 Park Visit 树的直径
- 替换空格
- 线性表链式存储API
- C++ 求排列函数 next_permutation, prev_permutation
- Intellij快捷键
- 指定Action,Category调用系统Activity
- CUDA Toolkit 各版本文档
- 动态显示当前系统时间和移除定时器
- C#静态字段和静态方法
- 指针练习 1002 将数组a中的n个整数按相反顺序存放
- 学习笔记(十二)—设计模式(续)
- JSON