C++ 程式在 STL 中實現 Next_Permutation


STL 中的 Next_permutation 可用來重新按順序將 [first, last] 範圍內的元素排列成更大的下一個詞法排列。排列是 N! 可能的元素排列中的每一個排列。本 C++ 程式在 STL 中實現了 Next_permutation。

演算法

Begin
   Define one integer array variable elements[].
   Get the number of data e from the user.
   Initialize the array elements[] with e number of data from the keyboard.
   Sort all the array elements.
   do
      show(elements, e) //to display the current content of the array
   while (next_permutation(elements, elements + e))
End

示例程式碼

#include<iostream>
#include <algorithm>
using namespace std;
void show(int a[], int n) {
   for(int i = 0; i < n; i++) {
      cout<<a[i]<<" ";
   }
   cout<<endl;
}
int main () {
   int e, i;
   cout<<"Enter number of elements to be inserted: ";
   cin>>e;
   int elements[e];
   for (i = 0; i < e; i++) {
      cout<<"Enter "<<i + 1<<" element: ";
      cin>>elements[i];
   }
   sort (elements, elements + e);
   cout << "The "<<e<<"! possible permutations with ";
   cout<<e<<" elements: "<<endl;
   do {
      show(elements, e);
   }
   while (next_permutation(elements, elements + e));
   return 0;
}

輸出

Enter number of elements to be inserted: 4
Enter 1 element: 7
Enter 2 element: 6
Enter 3 element: 2
Enter 4 element: 10
The 4! possible permutations with 4 elements:
2 6 7 10
2 6 10 7
2 7 6 10
2 7 10 6
2 10 6 7
2 10 7 6
6 2 7 10
6 2 10 7
6 7 2 10
6 7 10 2
6 10 2 7
6 10 7 2
7 2 6 10
7 2 10 6
7 6 2 10
7 6 10 2
7 10 2 6
7 10 6 2
10 2 6 7
10 2 7 6
10 6 2 7
10 6 7 2
10 7 2 6
10 7 6 2

更新於:30-7-2019

299 瀏覽次數

開啟你的 事業

透過完成課程獲得認證

開始學習
廣告
© . All rights reserved.