STL中next_permutation函数的应用-全排列(C++)

Posted 小张不胖

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了STL中next_permutation函数的应用-全排列(C++)相关的知识,希望对你有一定的参考价值。

next_permutation是algorithm库中的全排列函数,所以,我们用next_permutation函数的时候要加上头文件 #include <algorithm>,其强大的功能,可以解决我们写dfs,写完之后还要debug好久的烦恼。
格式为:next_permutation(arr,arr+n);
左边参数为数组的起始地址,右边参数为数组的结束地址 + 1 ,可以理解为一个左闭右开区间。
下面是几个实际应用例子:

  1. 全排列问题
    题目描述
    输出自然数 1 到 n 所有不重复的排列,即 n 的全排列,要求所产生的任一数字序列中不允许出现重复的数字。
    输入格式
    一个整数 n 。
    输出格式
    由 1 ~ n 组成的所有不重复的数字序列,每行一个序列,每个数字保留 5 个场宽。
    输入样例
3

输出样例

    1    2    3
    1    3    2
    2    1    3
    2    3    1
    3    1    2
    3    2    1

下面是我的AC代码

#include <iostream>
#include <algorithm>
#include <iomanip>
using namespace std;

int main()

	int a[9], i, n;
	cin >> n;
	for (i = 0; i < n; i++)
	
		a[i] = i + 1;
	
	do
	
		for (i = 0; i < n; i++)
		
			cout << setw(5) << setfill(' ') << a[i];//输出一个 5 位数,用空格填充
		
		cout << endl;
	 while (next_permutation(a, a + n));
	return 0;

  1. 组合的输出
    问题描述
    排列与组合是常用的数学方法,其中组合就是从 n 个元素中抽出 r 个元素(不分顺序且 r ≤ n),我们可以简单地将 n 个元素理解为自然数 1 , 2 , … , n ,从中任取 r 个数。
    现要求你输出所有组合。
    例如 n = 5 , r = 3 , 所有组合为:123,124,125,134,135,145,234,235,245,345。
    输入格式
    一行两个自然数 n , r ( 1 < n < 21 , 0 ≤ r ≤ n )。
    输出格式
    所有的组合,每一个组合占一行,且其中的元素按照由小到大的顺序排列,每个元素占三个字符的位置,所有的组合也按字典顺序。
    输入样例
5 3

输出样例

  1  2  3
  1  2  4
  1  2  5
  1  3  4
  1  3  5
  1  4  5
  2  3  4
  2  3  5
  2  4  5
  3  4  5

下面是我的AC代码

#include <iostream>
#include <algorithm>
#include <iomanip>
using namespace std;

int x[30], n, r, i;

int main()

    cin >> n >> r;
    for (i = n; i > r; i--)
    
        x[i] = 1;
    
    do
    
        for (i = 1; i <= n; i++)
        
            if (x[i] == 0)
            
                cout << setw(3) << setfill(' ') << i;
            
        
        cout << endl;
     while (next_permutation(x + 1, x + 1 + n));
    return 0;

以上是关于STL中next_permutation函数的应用-全排列(C++)的主要内容,如果未能解决你的问题,请参考以下文章

STL中next_permutation函数的应用-全排列(C++)

STL next_permutation排列

stl算法:next_permutation剖析

[OI - STL] next_permutation( ) & prev_permutation( )函数

STL::next_permutation();

C++STL的next_permutation