全排列理解和应用

全排列理解和应用,第1张

目录

全排列的理解:就是将一个数组进行多次顺序不同的排列方式;

一、学习next_permutation()函数:

代码和效果:

①:对升序数组进行全排列:

②:对乱序数组进行全排列 err!错误!(没有达到理想输出效果):

③:对降序数组进行全排列 err!错误!(没有达到理想输出效果):

④:对升序数组进行全排列 err!错误!(没有达到理想输出效果):使用while效果会少输出一组数据:

二、next_permutation()和sort()的完美结合运行:

三、 你乱任你乱,我玩我自己的! 自己写一个,自己玩!

总结和注意: 


全排列的理解:就是将一个数组进行多次顺序不同的排列方式;

例如:a[3]={1,2,3};

排列后输出:

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

基本就是这样。

一、学习next_permutation()函数:

C++头文件#include自带next_permutation()全排列函数;

注意:只能对升序数组有用!

代码和效果: ①:对升序数组进行全排列:

#include
#include
using namespace std;
int main() {
	int a[4] = { 1,2,3,4};
	do{
		cout << a[0] << " " << a[1] << " " << a[2] << " " << a[3] << endl;
	} while (next_permutation(a, a + 4));
	return 0;
}

输出:

②:对乱序数组进行全排列 err!错误!(没有达到理想输出效果):
#include
#include
using namespace std;
int main() {
	int a[4] = { 1,3,2,4};
	do{
		cout << a[0] << " " << a[1] << " " << a[2] << " " << a[3] << endl;
	} while (next_permutation(a, a + 4));
	return 0;
}

 输出:

③:对降序数组进行全排列 err!错误!(没有达到理想输出效果):

        

#include
#include
using namespace std;
int main() {
	int a[4] = {4,3,2,1};
	do{
		cout << a[0] << " " << a[1] << " " << a[2] << " " << a[3] << endl;
	} while (next_permutation(a, a + 4));
	return 0;
}

输出:

④:对升序数组进行全排列 err!错误!(没有达到理想输出效果):使用while效果会少输出一组数据:
#include
#include
using namespace std;
int main() {
	int a[4] = { 1,2,3,4 };
	while (next_permutation(a, a + 4)){
		cout << a[0] << " " << a[1] << " " << a[2] << " " << a[3] << endl;
	} 
	return 0;
}

 如:少输出1 2 3 4这一组数据!

二、next_permutation()和sort()的完美结合运行:

        先用sort()进行升序排列,再用next_permutation()岂不是完美?

        代码:

        

#include
#include
using namespace std;
int main() {
	int a[4] = {4,2,3,1};
	sort(a, a + 4);
	do{
		cout << a[0] << " " << a[1] << " " << a[2] << " " << a[3] << endl;
	} while (next_permutation(a, a + 4));
	return 0;
}

输出:

三、 你乱任你乱,我玩我自己的! 自己写一个,自己玩!
#include
#include
using namespace std;
int a[4] = { 4,2,3,1 };
void f(int n) {
	if (n == 4) {
		cout << a[0] << " " << a[1] << " " << a[2] << " " << a[3] << endl;
	}
	for (int i = n; i < 4; ++i)
	{	{
		int t = a[n];
		a[n] = a[i];
		a[i] = t;
		}
		f(n + 1); 
		{
			int t = a[n];
			a[n] = a[i];
			a[i] = t;
		}
	}

}
int main() {
	f(0);
	return 0;
}

总结和注意: 

        一、使用next_permutation()时,需要先升序再全排列,

               如果使用while()-do函数,则会少输出第一次的!

        二、sort()和next_permutation()可以完美配合使用!也可以自己写函数代码!

        三、希望给我大佬们多多指点,有问题就有进步!谢谢!

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/langs/662692.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-04-18
下一篇 2022-04-18

发表评论

登录后才能评论

评论列表(0条)

保存