27.Algorithm Gossip: permutations
Explanation
A set of numbers, letters or symbols arranged in order to obtain different combinations, for example of permutation and combination of these three digits 123 are:
1 2 3、1 3 2、2 1 3、2 3 1、3 1 2、3 2 1。
solution
Problems may be used to recursively cut into smaller units permutations and combinations, for example arrangement 1234 can be divided into
1 [2 3 4]、2 [1 3 4]、3 [1 2 4]、4 [1 2 3]
Arranges side by a spin method, a first rotation interval is set to 0, the rightmost digit is rotated to the left, and gradually increase the rotational intervals, for example:
1 2 3 4 -> 旋转1 -> 继续将右边2 3 4进行递回处理
2 1 3 4 -> 旋转1 2 变为 2 1-> 继续将右边1 3 4进行递回处理
3 1 2 4 -> 旋转1 2 3变为 3 1 2 -> 继续将右边1 2 4进行递回处理
4 1 2 3 -> 旋转1 2 3 4变为4 1 2 3 -> 继续将右边1 2 3进行递回处理
The sample code
#include <stdio.h>
#include <stdlib.h>
#define N 4
void perm(int*, int); int main(void) {
int num[N+1], i;
for(i = 1; i <= N; i++) num[i] = i;
perm(num, 1);
return 0;
}
void perm(int* num, int i) { int j, k, tmp;
if(i < N) {
for(j = i; j <= N; j++) { tmp = num[j];
// 旋转该区段最右边数字至最左边
for(k = j; k > i; k--)
num[k] = num[k-1]; num[i] = tmp; perm(num, i+1);
// 还原
for(k = i; k < j; k++) num[k] = num[k+1];
num[j] = tmp;
}
}
else { // 显示此次排列
for(j = 1; j <= N; j++) printf("%d ", num[j]);
printf("\n");
}
}