组合情况
# 前言
给定个互不相同的元素,要求从中取出个。
很显然,取出个不同组合的方法数有种。
那如果要求所有方案(并输出),该怎么办?
# Buckles's Solution(字典序最小)
long long Comb[20][20];
void init(int n){
comb[0][0] = 1;
for(int i=1; i<=n; i++){
comb[i][0] = 1;
for(int j=1; j<=i; j+++) comb[i][j] = comb[i-1][j] + comb[i-1][j-1];
}
}
/** [combination c n p x]
* get the [x]th lexicographically ordered set of [p] elements in [n]
* output is in [c], and should be sizeof(int)*[p] */
void combination(int* c,int n,int p, int x){
int i,r,k = 0;
for(i=0;i<p-1;i++){
c[i] = (i != 0) ? c[i-1] : 0;
do {
c[i]++;
r = Comb[n-c[i]][p-(i+1)];
k = k + r;
} while(k < x);
k = k - r;
}
c[p-1] = c[p-2] + x - k;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
# Python
print list(itertools.combinations('123', 2))
# [('1', '2'), ('1', '3'), ('2', '3')]
1
2
2
上次更新: 2021/02/24, 03:37:30