还是排列!
大家知道1 到 n的排列 有n!个 我这个要求不高 只要朋友们将 这n!个排列的前200个按字典顺序显示出来即可 不能出现重复和缺少的想象。
限制是 1 =< n <= 16.
比如 输入 n = 3 结果显示
1 2 3
1 3 2
2 1 3
2 3 1
3 1 2
3 2 1
记住一个排列占一行 如果能在每个排列前给个序号更好。
搞个百分贴 俺留的可用分忒多了点。
#include<iostream> #include<vector> #include<algorithm> #include<iterator> using namespace std; bool permutation(vector<int> &num) { int len = num.size() - 1; int top, tail,i; for(i=len; i>0; --i ) { if( num[i] > num[i-1]) { top = i; break; } } if(i == 0) return false; tail = top; for( i = len; i >=0; --i) { if(num[top-1] < num[i]) { tail = i; break; } } int tmp =num[top-1]; num[top-1] = num[tail]; num[tail] = tmp; for(int i=top, j = len; i<j; ++i, --j) { int tmp = num[i]; num[i] = num[j]; num[j] = tmp; } return true; } int main() { int n; cin >> n; long long f[20]={0,1,2}; for(int i=3; i<20; ++i) { f[i] = f[i-1] * i; } vector<int> num; num.reserve(n+1); for(int i=1; i<=n; ++i) { num.push_back(i); } copy(num.begin(), num.end(), ostream_iterator<int>(cout, " ")); cout << endl; int cas = 0; while(cas < 200 && (long long)cas < f[n]) { permutation(num); cout << cas++ << ": "; copy(num.begin(), num.end(), ostream_iterator<int>(cout, " ")); cout << endl; } return 0; }
#include <iostream> using namespace std; inline 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); } bool NextPermutation(int* start, int* end) { if (start >= end - 1) return false; int* sp = end - 2; /* Swap point */ while (sp >= start) { if (sp[0] < sp[1]) break; --sp; } if (sp < start) { Reverse(start, end); return false; } for (int* p = end - 1; p > sp; --p) if (*p > *sp) { Swap(sp, p); break; } Reverse(sp + 1, end); return true; } int main() { int array[16] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 }, n, i; cin >> n; do { cout << array[0]; for (i = 1; i < n; ++i) cout << " " << array[i]; cout << endl; } while (NextPermutation(array, array + n)); }