举个例子, 一个数组存放数据: 1, 2, 3, 4,, 那么这个数组的数据的所有permutation的个数为 4! = 24.。
实际中, 我们可以使用递归的办法去解决这个问题。
首先固定第一个数字, 接着固定第二个数字, 。。。。, 一个pass完成之后, 输出这个permutation, 接下来backtracking。
1, 2, 3,4
1, 2, 4, 3
1, 3, 2, 4
1, 3, 4, 2
1, 4, 3, 2
1, 4, 2, 3
2, .....
........
3.....
.......
等等方式求解。 不难看出, 上述的背后的数学公式是 n ! = n * (n-1)! 本身也是一个递归函数。 所以, 我们可以使用递归的办法解决。
同理, 对于字符a, b, c, d, 解决思路为:
a + permut(b, c, d)
b + permut(a, c, d)
c + permut(a, b, d)
d + perm(a, b, c)。
对应的程序如下:
void perm(int A[], int k, int n) {
if (k == n)
print A[0...n-1]
else { //a[k:n] has more than 1 perm
for (int i = k; i < n; i++) {
// in the loop, do n - k times swaps and fixed A[k]
t = A[k];
A[k] = A[i];
A[i] = t;
perm(A, k + 1, n); // find the permutation of shorter array
// when done, then we swap back
t = A[k];
A[k] = A[i];
A[i] = t;
}
}
当A[] = {1, 2, 3,}的时候, 调用方式: perm(A. , 0, 2)。
#include <iostream>
using namespace std;
void perm(int A[], int k, int n) {
if (k == n) {
for (int j = 0; j <= n; j++) {
cout << A[j] << " ";
}
cout << endl;
}
else { //a[k:n] has more than 1 perm
for (int i = k; i <= n; i++) {
// in the loop, do n - k times swaps and fixed A[k]
int t;
t = A[k];
A[k] = A[i];
A[i] = t;
perm(A, k + 1, n); // find the permutation of shorter array
// when done, then we swap back
t = A[k];
A[k] = A[i];
A[i] = t;
}
}
}
int main() {
int A[] = {1, 2, 3, 4};
perm(A, 0, 3);
return 0;
}
运行结果为: