制定查找所有可能排列的算法

时间:2015-06-26 13:32:16

标签: algorithm permutation

我发现通过简单地将最后一个元素与中间元素交换,然后通过第一个元素交换中间元素,可以轻松找到3个元素的排列,然后重复此直到找到所有排列。当有超过3个元素时我尝试应用它但它不起作用(对于n = 4我只发现12个排列),是否可以使它工作?我知道有一个由Steinhaus制作的算法 - Johnson - Trotter这可能就是我所说的但是我找不到他们算法的好解释。通过我不需要(伪)排列算法的代码。

2 个答案:

答案 0 :(得分:1)

递归地思考它,如果你有一组n个元素,然后生成所有可能的排列,将n个元素中的每一个放在第一个位置,然后生成其余元素的所有可能的排列并添加与第一个元素连接。

实现这一点的一种简单方法是定义一个函数,它将第一个元素依次与集合中的每个元素交换(包括它自己),然后递归调用自身以生成其余元素的每个可能的排列,以及然后在返回(回溯)后将元素交换回来。因为你说你不想要伪代码,所以很难详细说明。

这假定没有重复的元素。

工作示例:

Generate permutations of (1, 2, 3):

Put each element as the first element and then generate all permutations of remaining elements:

    0 + permutations of (1, 2)

       Put each element as the first element and then generate all permutations of remaining elements:

       0 + 1 + permutations of (2)

          Put each element as the first element and then generate all permutations of remaining elements:

             0 + 1 + 2

       0 + 2 + permutations of (1)

          Put each element as the first element and then generate all permutations of remaining elements:

             0 + 2 + 1

    1 + permutations of (0, 2)

       Put each element as the first element and then generate all permutations of remaining elements:

       1 + 0 + permutations of (2)

          Put each element as the first element and then generate all permutations of remaining elements:

             1 + 0 + 2

       1 + 2 + permutations of (0)

          Put each element as the first element and then generate all permutations of remaining elements:

             1 + 2 + 0

    2 + permutations of (0, 1)

       Put each element as the first element and then generate all permutations of remaining elements:

       2 + 0 + permutations of (1)

          Put each element as the first element and then generate all permutations of remaining elements:

             2 + 0 + 1

       2 + 1 + permutations of (0)

          Put each element as the first element and then generate all permutations of remaining elements:

             2 + 1 + 0

答案 1 :(得分:0)

在java代码中实现@samgak算法

/**
* Created by Balachandar on 21-01-2017.
*/
public class Permutation {

    public static void permutation(String input, String ans)
    {
        if(input.isEmpty()){

            System.out.println(ans);

        }
        else {
            for (int i = 0; i < input.length(); i++) {

                permutation( input.substring(0, i) + input.substring(i + 1, input.length()),ans + input.charAt(i));
            }
        }
    }
    public static void main(String[] args)
    {
        permutation("abcd","");
    }
}
相关问题