博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
排列组合算法(基于c++实现)
阅读量:4316 次
发布时间:2019-06-06

本文共 2115 字,大约阅读时间需要 7 分钟。

排列

全排列是将一组数按一定顺序进行排列,如果这组数有n个,那么全排列数为n!个。现以{1, 2, 3}为例说明如何编写全排列的递归算法

第一层S1表示第一个数分别与第1、2、3个数交换位置,如123是1和第一个数1交换,213是1和第二个数2交换,321是1和第三个数交换

第二层S2是第二个数分别与第2、3个数交换位置。则最后一层的所有叶子节点,即为全排列的所有结果。第k层中的节点Sk就是父节点中的第k个数,分别与第k、k+1...n个数交换位置。

也可用stl的next_permutation()和perv_permutation()

#include 
#include
#include
using namespace std;template
class Perm{ public: //由于vector本身就是模板,在其模板参数未确定之前,也就是具体类型没有确定之前,这个T是未知的 //typename就是告诉编译器先不管具体类型,等模板实例化的时候再确定 void perm(vector
&a,typename vector
::iterator begin); bool is_swap(typename vector
::iterator i,typename vector
::iterator j); private: static int i;};template
int Perm
::i=0;template
bool Perm
::is_swap(typename vector
::iterator i,typename vector
::iterator j){ for(typename vector
::iterator k=i;k!=j;++k) if(*k==*j) return false; return true; }template
void Perm
::perm(vector
&a,typename vector
::iterator begin){ if(begin==a.end()) { cout<<" 第"<<++i<<" 个排列为:"; for_each(a.begin(),a.end(),[](int i) { cout<
<<" "; }); cout<
a; int n; cout<<" 请输入元素的个数:"<
>n; for(int i=0;i
>t; a.push_back(t); } Perm
p; p.perm(a,a.begin()); return 0;}

 组合

第一层S1中的节点是数组中的所有数字,第二次S2中的节点是分别从父节点的下一个位置开始。因为这个例子中m=2,所以共有2层。从第一层到第二层,深度遍历这颗树,即可得到所有组合。

#include 
#include
#include
using namespace std;template
class Combine{ public: void combine(vector
a,int begin,int num); private: vector
r;};template
void Combine
::combine(vector
a,int begin,int num){ if(a.empty()) { cout<<" 要组合的数组为空."<
a; int n; cout<<" 请输入元素的个数:"<
>n; for(int i=0;i
>t; a.push_back(t); } int num; cout<<" 请输入要选择的个数:"<
>num; Combine
c; c.combine(a,0,num); return 0;}

 执行过程:

  第一次for也就是开始:beign=0,i=0,num=2;进入下一次递归也就是第二次for循环,beign=1,i=1,num=1;第三次递归时num==0,输出,本次递归结束。返回到第二次递归也就是第二次for循环,i自增1

  在第二次for循环里面进行递归也就是第四次for循环(有点绕。。。),begin=1,i=2,num=1;第五次for循环时num==0,结束本次递归,退回到第二次for循环;i自增1,结果不符合for循环条件,第二次

  for循环结束;以此推。。。(黑体加粗为同一层for循环)

 

转载于:https://www.cnblogs.com/tianzeng/p/10055489.html

你可能感兴趣的文章
史玉柱自述:我是如何带队伍的
查看>>
靶形数独【贪心+深搜】
查看>>
读大道至简第三章有感
查看>>
BeforeFieldInit的小叙
查看>>
TeamViewer的下载地址,低调低调
查看>>
005 线程ID和线程的优先级
查看>>
POJ 3067 Japan (树状数组 && 控制变量)
查看>>
python基础条件和循环
查看>>
an exciting trip
查看>>
【转】xmind8 破解激活教程
查看>>
Mysql用命令方式启动服务
查看>>
【贪心】codeforces A. Heidi and Library (easy)
查看>>
【leetcode】lower_bound
查看>>
跨站请求伪造(CSRF)
查看>>
EF Code First数据库映射规则及配置
查看>>
.Net StackFrame
查看>>
Qt 学习之路:视图选择 (QItemSelectionModel)
查看>>
QStyleFactory类参考
查看>>
ng-深度学习-课程笔记-2: 神经网络中的逻辑回归(Week2)
查看>>
正则表达式的搜索和替换
查看>>