C/C++實現(xiàn)全排列算法的示例代碼
1、全排列的介紹
從n個不同元素中任取m(m≤n)個元素,按照一定的順序排列起來,叫做從n個不同元素中取出m個元素的一個排列。當m=n時所有的排列情況叫全排列。
2、方法和思路
進行窮舉法和特殊函數(shù)的方法,窮舉法的基本思想是全部排列出來.特殊函數(shù)法進行特殊排列.
3、窮舉法
【不包含重復數(shù)字的解法】
#include <iostream> using namespace std; int main() { int a[3]; cout << "請輸入一個三位數(shù):" << endl; for (int m = 0; m < 3; m++) { cin >> a[m]; } for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { for (int k = 0; k < 3; k++) { if (i != j && i != k && j != k) { cout << a[i] << a[j] << a[k] << " "; } } } } }
【包含重復數(shù)據(jù)的解法】
#include <iostream> using namespace std; int main() { int a[3]; cout << "請輸入一個三位數(shù):" << endl; for (int m = 0; m < 3; m++) { cin >> a[m]; } for ( int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { for (int k = 0; k < 3; k++) { if (i != j && i != k && j != k) { cout << a[i] << a[j] << a[k] << " "; } else if(i==j&&i==k&&j==k) { cout << a[i] << a[j] << a[k] << " "; } } } } }
4、next_permutation()函數(shù)法而且調(diào)用了sort()排序函數(shù)
什么是sort函數(shù)?
這種方法也是小編特別推薦使用的,因為這種方法不僅可以高效的進行排序而且特別容易理解.
next_permutation(s1.begin(), s1.end())
解釋:s1.begin(),是字符串的開頭,s1.end()是字符串的結尾
頭文件:
#include <algorithm>
4.1、升序
#include <iostream> #include <algorithm> #include <string.h> using namespace std; int main() { string s1; cout << "請輸入您要的數(shù)據(jù):" << endl; cin >> s1; do { cout << s1 << " "; } while (next_permutation(s1.begin(), s1.end())); }
4.2、降序
bool cmp(int a, int b) { return a > b; }
while (next_permutation(s1.begin(), s1.end(),cmp));
sort(s1.begin(), s1.end(), cmp);
比升序多了以上三個數(shù)據(jù)
#include <iostream> #include <algorithm> #include <string.h> using namespace std; bool cmp(int a, int b) { return a > b; } int main() { string s1; cout << "請輸入您要的數(shù)據(jù):" << endl; cin >> s1; sort(s1.begin(), s1.end(), cmp); do { cout << s1 << " "; } while (next_permutation(s1.begin(), s1.end(),cmp)); }
5、總結
有窮法具有有限性,然而特殊函數(shù)法會較好的解決了這個問題
到此這篇關于C/C++實現(xiàn)全排列算法的示例代碼的文章就介紹到這了,更多相關C++ 全排列算法內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
C++使用cuBLAS加速矩陣乘法運算的實現(xiàn)代碼
這篇文章主要介紹了C++使用cuBLAS加速矩陣乘法運算,將cuBLAS庫的乘法運算進行了封裝,方便了算法調(diào)用,具體實現(xiàn)代碼跟隨小編一起看看吧2021-09-09