upd 2023/6/3:
本文已经发布进阶版,代码效率比此篇高,有需求的读者可以来阅读
【C++】 排列与组合算法详解(进阶篇)https://blog.csdn.net/xingchen_2008/article/details/130782915
嘿!好久不见……
今天我又来 水文章 发文章了
今天来介绍一下非常垃圾的排列组合算法
声明:本篇文章含有手残作者画的图,大家不要介意(*_*)
学过数学的都知道,组合用 表示,排列用
或
表示
所谓组合,就是在 个东西中无顺序地拿
个东西
,所有不重不漏的情况的个数
如:
用算术方法的话,就是
;
同理,
。
我们可以继而推导出组合的一般公式:(! 代表阶乘)
以及排列的一般公式:
先放个算阶乘的代码:
int fact(int x)//阶乘代码
{
int res = 1;//返回值变量
for (int i = x; i; i -- )//用for实现逐次减一
res *= i;//乘入返回值变量
return res;//返回
}
再用代码实现排列组合:
int C(int x, int y)//定义组合函数
{
int ret;
ret = fact(x) / fact(x - y) / fact(y);//公式
return ret;
}
int A(int x, int y)//定义排列函数
{
int ret;
ret = fact(x) / fact(y);//公式
return ret;
}
完整代码
#include <iostream>
#define int long long
using namespace std;
int fact(int x)
{
int res = 1;
for (int i = x; i; i -- )
res *= i;
return res;
}
int C(int x, int y)
{
int ret;
ret = fact(x) / fact(x - y) / fact(y);
return ret;
}
int A(int x, int y)
{
int ret;
ret = fact(x) / fact(y);
return ret;
}
signed main()
{
ios::sync_with_stdio(false);
cin.tie(0), cout.tie(0);
int a, b;
cin >> a >> b;
cout << "组合:" << C(a, b) << endl;
cout << "排列:" << A(a, b) << endl;
return 0;
}
最终效果
本期的 文章就到这里了,点个赞,点个关注 ,感谢你们~