bool next_permutation(beg,end)
bool prev_permutation(beg,end)
next_permutation()会改变区间[beg,end)内的元素次序,使它们符合“下一个排列次序”;
prev_permutation()会改变区间[beg,end)内的元素次序,使它们符合“上一个排列次序”;
如果元素得以排列成(就字典顺序而言的)"正规"次序,则两个算法都返回true。所谓正规次序,对next_permutation()而言为升序,对perv_permutation()而言为降序。因此,如果要走遍所有排列,你必须先将所有元素(按升序或降序)排序,然后开始以循环方式调用next_permutation或prev_permutation,直到算法返回false;
复杂度:线性
代码示例:
#include"fuzhu.h"using namespace std;int main(){vector<int> coll;INSERT_ELEMENTS(coll,1,3);PRINT_ELEMENTS(coll,"on entry: ");//1 2 3while(next_permutation(coll.begin(),coll.end()))//从小到大,输出到3 2 1 后,再次执行next_permutation()后为false,执行后为 1 2 3{PRINT_ELEMENTS(coll," ");}PRINT_ELEMENTS(coll,"afterward: ");//1 2 3while(prev_permutation(coll.begin(),coll.end()))//未输出,因为1 2 3的上一个序列为3 2 1,不满足降序,虽然返回为flase,但是序列会变为3 2 1{PRINT_ELEMENTS(coll," ");}PRINT_ELEMENTS(coll,"now: ");//3 2 1while(prev_permutation(coll.begin(),coll.end()))//从大到小{PRINT_ELEMENTS(coll);}PRINT_ELEMENTS(coll,"afterward: ");//3 2 1system("pause");return 0;}
运行结果: