12 21
123 132 213 231 321 312
....
每次都将后面n-1位进行全排列。递归的出口当起始坐标等于终止坐标时。需要还原。
设计标记数组。因为需要从小到大输出。
#define _CRT_SECURE_NO_DEPRECATE#include#include #include #include #include using namespace std;int visited[10010];int a[4];void swap(int a[], int i, int j){ int temp = a[i]; a[i] = a[j]; a[j] = temp;}void perm(int a[], int k, int m, int pk, int pm){ if (k == m) { int sum = 0; for (int i = pk; i <= pm; i++) { sum = sum * 10 + a[i]; } visited[sum] = 1; } else { for (int i = k; i <= m; i++) { swap(a, k, i); perm(a, k + 1, m, pk, pm); swap(a, k, i); } }}int main(){ int t = 0; while (scanf("%d", &a[0]) != EOF) { scanf("%d%d%d", &a[1], &a[2], &a[3]); if (a[1] == 0 && a[2] == 0 && a[0] == 0 && a[3] == 0) break; if (t != 0) printf("\n"); t = 1; sort(a, a + 4); memset(visited, 0, sizeof(visited)); perm(a, 0, 3, 0, 3); int k; int sign = 0; for (int i = 1000; i < 10000; i++) { if (visited[i]==1) { sign++; if (sign== 1) { k = i / 1000; printf("%d", i); } else { if (i / 1000 != k) { printf("\n"); k = i / 1000; } else printf(" "); printf("%d", i); } } } printf("\n"); } return 0;}