枚举生成1-n的排列
#define L 5 int N[L] = {1,2,3,4,5}; void print_permutation(int n, int *a, int cur) { if ( cur == n ) { for ( int i = 0; i < n; i++ ) { printf("%d ", a[i]); } printf("\n"); } else { for ( int i = 0; i < n; i++ ) { int has = 0; for ( int j = 0; j < cur; j++ ) { if ( a[j] == N[i] ) has = 1; } if (!has ) { a[cur] = N[i]; print_permutation(n,a,cur+1); } } } } int main() { int a[L] = {0}; print_permutation(L, a, 0); return 0; }
还可以直接使用C++提供的STL (原来还可以这样啊摔!)
int main () { int n, p[10]; scanf("%d", &n); for (int i = 0; i < n; i++) scanf("%d", &p[i]); sort(p, p+n); do { for (int i = 0; i < n; i++ ) printf("%d", p[i]); printf("\n"); } while(next_permutation(p, p+n)); system("PAUSE"); return 0; }