组合与排列的表达:pascal三角形和母函数

杨辉三角和母函数都能表达不同问题的组合结果,杨辉有利于打表存储且运算快,母函数则能更好体现了组合的思想和过程。已知C(n,m)=A(n,m)/m!=n!/(n-m)!/m!,对于如下的n和m:
3 2
5 3
9 5
10 5
16 8
20 10
约定: 1<=m<=n<=20.
杨辉三角:
#include <iostream>
#include<cstdio>
using namespace std;
typedef long long LL;
LL fac[21][21];  
void init(){
    for(int i=0;i<21;i++){
        fac[i][0]=fac[i][i]=1;
        for(int j=1;j<i;j++){
            fac[i][j]=fac[i-1][j-1]+fac[i-1][j];
        }
    }
}
int main()
{
	freopen("cin.txt","r",stdin);
    freopen("cout.txt","w",stdout);
    int n,m;
    init();
    while(cin>>n>>m){
        cout<<fac[n][m]<<endl;
    }
    return 0;
}
结果:
3
10
126
252
12870
184756

母函数将C(n,m)=A(n,m)/m!=n!/(n-m)!/m! 表示为:g(x)=(1+x+x^2+……)^n
#include <iostream>
#include<cstdio>
#include<cstring>
using namespace std;
typedef long long LL;
//C(n,m)=A(n,m)/m!  g(x)=(1+x+x^2+……)^n
LL c1[21],c2[21];
int main()
{
    freopen("cin.txt","r",stdin);
    freopen("cout.txt","w",stdout);
    int n,m;
    while(cin>>n>>m){
        int i,j,k;
        memset(c1,0,sizeof(c1));
        memset(c2,0,sizeof(c2));
        c1[0]=c1[1]=1;
        for(i=1;i<n;i++){
            for(j=0;j<=n;j++)c2[0+j]+=c1[j];
            for(j=0;j<n;j++)c2[1+j]+=c1[j]; //下标代表x的指数,值表示系数,也就是最终的组合数。
            for(j=0;j<=n;j++){
                c1[j]=c2[j];
                c2[j]=0;
            }
        }
        for(i=0;i<=20;i++) cout<<c1[i]<<" "; cout<<endl;
        cout<<c1[m]<<endl;
    }
    return 0;
}
结果:
1 3 3 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
3
1 5 10 10 5 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
10
1 9 36 84 126 126 84 36 9 1 0 0 0 0 0 0 0 0 0 0 0
126
1 10 45 120 210 252 210 120 45 10 1 0 0 0 0 0 0 0 0 0 0
252
1 16 120 560 1820 4368 8008 11440 12870 11440 8008 4368 1820 560 120 16 1 0 0 0 0
12870
1 20 190 1140 4845 15504 38760 77520 125970 167960 184756 167960 125970 77520 38760 15504 4845 1140 190 20 1
184756
那么对于排列A(n,m)则只需要在上面的基础上再乘以m!即可。用int和long long表达阶乘范围有限,int: 13!  LL: 20!。由下面的代码测试得到:
    LL n,m,i;
    for(m=1,i=2;;i++){
        n=m;
        m*=i;
        if(m<n) break;
    }
    printf("The max number is %I64d.\n",i-1);
嘿嘿,这也就是为什么我们刚刚约定n<=20。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值