使用STL的next_permutation函数生成全排列(C++)
下午研究了一下全排列算法,然后發現C++的STL有一個函數可以方便地生成全排列,這就是next_permutation
在C++ Reference中查看了一下next_permutation的函數聲明:
#include <algorithm>
bool next_permutation( iterator start, iterator end );
The?next_permutation() function attempts to transform the given range of elements [start,end) into the next lexicographically greater permutation of elements. If it succeeds, it returns true, otherwise, it returns false.
從說明中可以看到 next_permutation 的返回值是布爾類型。按照提示寫了一個標準C++程序:
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | #include <iostream> #include <algorithm> #include <string>using namespace std;int main() {string str;cin >> str;sort(str.begin(), str.end());cout << str << endl;while (next_permutation(str.begin(), str.end())){cout << str << endl;}return 0; } |
其中還用到了 sort 函數和 string.begin()、string.end() ,函數聲明如下:
#include <algorithm>
void sort( iterator start, iterator end );
sort函數可以使用NlogN的復雜度對參數范圍內的數據進行排序。
#include <string>
iterator begin();
const_iterator begin() const;
#include <string>
iterator end();
const_iterator end() const;
string.begin()和string.end() 可以快速訪問到字符串的首字符和尾字符。
在使用大數據測試的時候,發現標準C++的效率很差...換成C函數寫一下,效率提升了不止一倍...
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | #include <cstdio> #include <algorithm> #include <cstring> #define MAX 100using namespace std;int main() {int length;char str[MAX];gets(str);length = strlen(str);sort(str, str + length);puts(str);while (next_permutation(str, str + length)){puts(str);}return 0; } |
《新程序員》:云原生和全面數字化實踐50位技術專家共同創作,文字、視頻、音頻交互閱讀
總結
以上是生活随笔為你收集整理的使用STL的next_permutation函数生成全排列(C++)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 排列组合算法的实现代码
- 下一篇: next_permutation函数