在C++中使用STL进行数组的所有排列

2021年3月12日14:36:41 发表评论 733 次浏览

给定一个数组, 任务是使用C ++中的STL打印或显示此数组的所有排列。

例子:

Input: a[] = {1, 2, 3}
Output:
1  2  3  
1  3  2  
2  1  3  
2  3  1  
3  1  2  
3  2  1  

Input: a[] = {10, 20, 30, 40}
Output:
10  20  30  40  
10  20  40  30  
10  30  20  40  
10  30  40  20  
10  40  20  30  
10  40  30  20  
20  10  30  40  
20  10  40  30  
20  30  10  40  
20  30  40  10  
20  40  10  30  
20  40  30  10  
30  10  20  40  
30  10  40  20  
30  20  10  40  
30  20  40  10  
30  40  10  20  
30  40  20  10  
40  10  20  30  
40  10  30  20  
40  20  10  30  
40  20  30  10  
40  30  10  20  
40  30  20  10

推荐:请尝试以下方法{IDE}首先, 在继续解决方案之前。

方法:数组的下一个可能置换可以使用next_permutation()STL中提供的功能。

语法如下:

bool next_permutation (BidirectionalIterator first, BidirectionalIterator last);

下面是上述方法的实现:

// C++ program to display all permutations
// of an array using STL in C++
  
#include <bits/stdc++.h>
using namespace std;
  
// Function to display the array
void display( int a[], int n)
{
     for ( int i = 0; i < n; i++) {
         cout << a[i] << "  " ;
     }
     cout << endl;
}
  
// Function to find the permutations
void findPermutations( int a[], int n)
{
  
     // Sort the given array
     sort(a, a + n);
  
     // Find all possible permutations
     cout << "Possible permutations are:\n" ;
     do {
         display(a, n);
     } while (next_permutation(a, a + n));
}
  
// Driver code
int main()
{
  
     int a[] = { 10, 20, 30, 40 };
  
     int n = sizeof (a) / sizeof (a[0]);
  
     findPermutations(a, n);
  
     return 0;
}

输出如下:

Possible permutations are:
10  20  30  40  
10  20  40  30  
10  30  20  40  
10  30  40  20  
10  40  20  30  
10  40  30  20  
20  10  30  40  
20  10  40  30  
20  30  10  40  
20  30  40  10  
20  40  10  30  
20  40  30  10  
30  10  20  40  
30  10  40  20  
30  20  10  40  
30  20  40  10  
30  40  10  20  
30  40  20  10  
40  10  20  30  
40  10  30  20  
40  20  10  30  
40  20  30  10  
40  30  10  20  
40  30  20  10

被认为是行业中最受欢迎的技能之一, 我们拥有自己的编码基础C ++ STL通过激烈的问题解决过程来训练和掌握这些概念。


木子山

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: