且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

没有递归的置换算法?爪哇

更新时间:2023-11-24 09:09:40

你应该使用这样一个事实:当你想要 N 个数字的所有排列时,有 N 个!可能性.因此每个数字 x 来自 1..N!编码这样的排列.这是一个迭代打印出所有排列的示例.

You should use the fact that when you want all permutations of N numbers there are N! possibilities. Therefore each number x from 1..N! encodes such a permutation. Here is a sample that iteratively prints out all permutations of a sting.

private static void printPermutationsIterative(String string){
        int [] factorials = new int[string.length()+1];
        factorials[0] = 1;
        for (int i = 1; i<=string.length();i++) {
            factorials[i] = factorials[i-1] * i;
        }

        for (int i = 0; i < factorials[string.length()]; i++) {
            String onePermutation="";
            String temp = string;
            int positionCode = i;
            for (int position = string.length(); position > 0 ;position--){
                int selected = positionCode / factorials[position-1];
                onePermutation += temp.charAt(selected);
                positionCode = positionCode % factorials[position-1];
                temp = temp.substring(0,selected) + temp.substring(selected+1);
            }
            System.out.println(onePermutation);
        }
    }