当前位置:网站首页>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 .总结
有穷法具有有限性,然而特殊函数法会较好的解决了这个问题
边栏推荐
猜你喜欢
MySQL 中 is null 和 =null 的区别
删除文件夹时,报错“错误ox80070091:目录不是空的”,该如何解决?
MySQL——几种常见的嵌套查询
Redis实现分布式锁
DOM0, DOM2, DOM3 events
面试突击71:GET 和 POST 有什么区别?
二叉查找树的插入
go中select语句
Rabbit and Falcon are all covered, Go lang1.18 introductory and refined tutorial, from Bai Ding to Hongru, the whole platform (Sublime 4) Go lang development environment to build EP00
SQL exam questions
随机推荐
GO开发环境配置
pytorch安装错误
MySQL的分页你还在使劲的limit?
Go的Gin框架学习
PostgreSQL的架构
STP生成树(端口状态+端口角色+收敛机制 )|||| STP优化技术( uplinkfast技术+Portfast技术+backbonefast技术 )详解
AD环境搭建
redis实现分布式锁的原理
Validate floating point input
删除文件夹时,报错“错误ox80070091:目录不是空的”,该如何解决?
机器学习(公式推导与代码实现)--sklearn机器学习库
015-Balanced binary tree (1)
STP和RSTP的BPDU报文中flag位 对比+分析
Oracle数据库表空间整理回收与释放操作
超详细的Asp.net使用SSL双向认证,一篇就够了
Go Redis database operation
Promise 一: 基本问题
MySQL 中 is null 和 =null 的区别
函数指针数组
MySQL8重置root账户密码图文教程