在C++的标准函数库STL中,next_permutation()函数用于求数列的全排列。
代码:
例子1(int型):int main(){ int a[] = {3,1,2}; do{ cout << a[0] << " " << a[1] << " " << a[2] << endl; }while (next_permutation(a, a+3)); return 0;}输出:312/321 因为原数列不是从最小字典排列开始。
所以要想得到所有全排列int a[] = {3,1,2}; 然后先排序为:a[] = {1,2,3};
例子2(string型)int main(){ string str; cin >> str; sort(str.begin(), str.end()); do{ cout << str << endl; }while (next_permutation(str.begin(), str.end())); return 0;}
库中另一函数prev_permutation()与next_permutation()相反
本文介绍C++标准函数库STL中的next_permutation()函数,该函数用于求数列的所有可能排列。通过两个示例,分别演示了对整型数组和字符串进行全排列的方法。同时提及了prev_permutation()函数,它与next_permutation()作用相反。
1248

被折叠的 条评论
为什么被折叠?



