N个元素中取出M个元素的所有排列
#include #define MAX 10int used[MAX]; int result[MAX]; int M, N;void print() { int i; for(i = 0; i < M; i++) printf("%d ", result[i]); printf("\n");}void Perm(int step) { int i; if (step == M) print(); else for(i = 0; i < N; i++) if (!used[i]) { used[i] = 1; result[step] = i + 1; Perm(step + 1); used[i] = 0; }}main() { scanf("%d %d", &M, &N); Perm(0); }
N个元素中取出M个元素的所有组合
#include#define MAX 20int c[MAX] = {0};int M, N;void print() { int i; for(i = 0; i < M; i++) printf("%d", c[i + 1]); printf("\n");}void Comp(int m) { if (m == M + 1) print(); else for(c[m] = c[m - 1] + 1; c[m] <= N - M + m; c[m]++) Comp(m + 1);}void main() { scanf("%d %d", &M, &N); Comp(1);}