欢迎您访问 最编程 本站为您分享编程语言代码,编程技术文章!
您现在的位置是: 首页

用递归和C++ next_permutation方法实现的全排列双解法探究

最编程 2024-07-27 08:20:31
...

1.递归写法

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

int a[5] = { 1, 2, 3, 4, 5 }; 

void next(int k)
{
	if(k == 5)
	{
		for(int i = 0; i < 5; i++)
		{
			printf("%d ", a[i]);
	    }
	    printf("\n");
		return; 
	}
	if(k > 5) return;
	for(int i = k; i < 5; i++)
	{
		swap(a[i], a[k]);
		next(k + 1);
		swap(a[i], a[k]);
    } 
} 
int main()
{
	next(0);
	
	return 0;
}

2、next_permutation函数

技巧:next_permutation()函数是输出本排列的下一个排列!!!!。

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

const int N = 1e5;
int a[N];
int n;

int main()
{
	cin >> n;
	for(int i = 0; i < n; i++) cin >> a[i];
	
	do{
		for(int i = 0; i < n; i++) cout << a[i] << " ";
		cout << endl;
	}while(next_permutation(a, a + n));
	
	return 0;
}