回复 10楼 lz1091914999
这个 不错 如果排列前给个序号就圆满了。
梅尚程荀
马谭杨奚
#include<stdio.h> void print_permutation(int n, int deep, int max) { static int * p, c; int i, j, t; if(deep == 0) { p = (int *)malloc(n * sizeof(int)); for(i = 0; i < n; i++) p[i] = i + 1; c = 0; } if(deep >= n) { printf("%4d : ", ++c); for(i = 0; i < n; printf("%-4d", p[i++])); puts(""); return; } for(i = deep; i < n && c < max; i++) { t = p[deep]; p[deep] = p[i]; p[i] = t; print_permutation(n, deep + 1, max); } for(t = p[i = deep]; i < n - 1; i++) p[i] = p[i + 1]; p[n - 1] = t; if(deep == 0) free(p); } int main() { int n; while(scanf("%d", &n), n) print_permutation(n, 0, 200); return 0; }
#include <stdio.h> #include <math.h> void Swap(int* p1, int* p2) { int tmp = *p1; *p1 = *p2; *p2 = tmp; } void Reverse(int* start, int* end) { while (start < end) Swap(start++, --end); } unsigned fac(unsigned n) { unsigned i, result = 1; for (i = 2; i <= n; ++i) result *= i; return result; } int NextPermutation(int* start, int* end) { int* p, *sp = end - 2; if (start >= end - 1) return 0; while (sp >= start) { if (sp[0] < sp[1]) break; --sp; } if (sp < start) { Reverse(start, end); return 0; } for (p = end - 1; p > sp; --p) if (*p > *sp) { Swap(sp, p); break; } Reverse(sp + 1, end); return 1; } int main() { unsigned lineNumber = 0; int array[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 }, n, i, width; char format[8]; /* %xxu:%3d */ scanf("%d", &n); width = (int)log10(fac(n)) + 1; sprintf(format, "%%%du:%%3d", width); do { printf(format, ++lineNumber, array[0]); for (i = 1; i < n; ++i) printf("%3d", array[i]); putchar('\n'); } while (NextPermutation(array, array + n)); return 0; }这样可以了吧?