常用小函数集锦

求组合数(适用于60内的排列组合)

long long  gcd ( long long  x,long long  y){
	if(y==0) return x>y?x:y;
	int t=x%y;
	while(t){  x=y,y=t,t=x%y;   }
	return y;
}
long long C(int a,int b){
	long long mu=1,zi=1;
	long long int n=b<a-b?b:a-b;
	for(int i=1,te=a;i<=n;i++,te--){
		mu*=te;
		zi*=i;
		long long int temp = gcd(mu,zi);
		mu/=temp;
		zi/=temp;
	}
	return mu/zi;
}


输出排列组合(从小到大)

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
void printResult(vector<int>& vecInt, int t[]){
 for(int i = 0; i < vecInt.size(); ++i)
   if(vecInt[i] == 1)
      cout << t[i] << " ";
 cout << endl;
}
bool compare(int a, int b){
 if(a > b)
  return true;
return false;
}
void combination(int t[], int c, int total){
 vector<int> vecInt(total,0);
 for(int i = 0; i < c; ++i)  vecInt[i] = 1;
 printResult(vecInt, t);
 for(int i = 0; i < total - 1; ++i)
  if(vecInt[i] == 1 && vecInt[i+1] == 0){
   swap(vecInt[i], vecInt[i+1]);
   sort(vecInt.begin(),vecInt.begin() + i, compare);
   printResult(vecInt, t);
   i = -1;
  }
}
int main()
{
 const int N = 5;
 int t[N] = {1, 2, 3, 4, 5};
 combination(t, 3, N);
 system("pause");
 return 0;
}


原文地址:https://www.cnblogs.com/zswbky/p/5431963.html