您的位置:首页 > 其它

find all the permutation of a string

2014-10-20 16:31 344 查看
举个例子, 一个数组存放数据: 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;
}


运行结果为:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐