当前位置:网站首页>57.【全排列的详细分析】
57.【全排列的详细分析】
2022-08-03 09:48:00 【李在奋斗……】
1.1 全排列的介绍
从n个不同元素中任取m(m≤n)个元素,按照一定的顺序排列起来,叫做从n个不同元素中取出m个元素的一个排列。当m=n时所有的排列情况叫全排列。
2.1 方法和思路
进行穷举法和特殊函数的方法,穷举法的基本思想是全部排列出来.特殊函数法进行特殊排列.
3.1 穷举法
【不包含重复数字的解法】
#include <iostream>
using namespace std;
int main()
{
int a[3];
cout << "请输入一个三位数:" << endl;
for (int m = 0; m < 3; m++)
{
cin >> a[m];
}
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
for (int k = 0; k < 3; k++)
{
if (i != j && i != k && j != k)
{
cout << a[i] << a[j] << a[k] << " ";
}
}
}
}
}【包含重复数据的解法】
#include <iostream>
using namespace std;
int main()
{
int a[3];
cout << "请输入一个三位数:" << endl;
for (int m = 0; m < 3; m++)
{
cin >> a[m];
}
for ( int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
for (int k = 0; k < 3; k++)
{
if (i != j && i != k && j != k)
{
cout << a[i] << a[j] << a[k] << " ";
}
else if(i==j&&i==k&&j==k)
{
cout << a[i] << a[j] << a[k] << " ";
}
}
}
}
}4.1 next_permutation()函数法而且调用了sort()排序函数
什么是sort函数? http://t.csdn.cn/Tq9Wn
这种方法也是小编特别推荐使用的,因为这种方法不仅可以高效的进行排序而且特别容易理解.
next_permutation(s1.begin(), s1.end())解释:s1.begin(),是字符串的开头,s1.end()是字符串的结尾
头文件:
#include <algorithm>4.1.1 升序
#include <iostream>
#include <algorithm>
#include <string.h>
using namespace std;
int main()
{
string s1;
cout << "请输入您要的数据:" << endl;
cin >> s1;
do
{
cout << s1 << " ";
} while (next_permutation(s1.begin(), s1.end()));
} 
4.1.2 降序
bool cmp(int a, int b)
{
return a > b;
}while (next_permutation(s1.begin(), s1.end(),cmp));sort(s1.begin(), s1.end(), cmp);
比升序多了以上三个数据
#include <iostream>
#include <algorithm>
#include <string.h>
using namespace std;
bool cmp(int a, int b)
{
return a > b;
}
int main()
{
string s1;
cout << "请输入您要的数据:" << endl;
cin >> s1;
sort(s1.begin(), s1.end(), cmp);
do
{
cout << s1 << " ";
} while (next_permutation(s1.begin(), s1.end(),cmp));
}
5 .总结
有穷法具有有限性,然而特殊函数法会较好的解决了这个问题
边栏推荐
猜你喜欢
随机推荐
流水线设计的方法和作用「建议收藏」
二叉查找树的综合应用
ClickHouse查询语句详解
Can't get data for duplicate urls using Scrapy framework, dont_filter=True
Mysql 主从复制 作用和原理
013-Binary tree
MySQL 如何修改SQL语句,去掉语句中的or
bihash总结
mysql 事务原理详解
Promise 一: 基本问题
For heavy two-dimensional arrays in PHP
php中去重二维数组
Scrapy + Selenium implements simulated login and obtains dynamic page loading data
ClickHouse删除数据之delete问题详解
决策树和随机森林
函数指针数组
RSTP(端口角色+端口状态+工作机制)|||| 交换机接口分析
Redis和Mysql数据同步的两种方案
Unity笔记之简陋的第一人称漫游
MySQL的存储过程










