Print all permutation in lexicographic order

前端 未结 9 2051
悲哀的现实
悲哀的现实 2020-11-30 10:04

I want to print all permutation of string in lexicographic order. I wrote this code:

void permute(char *a, int i, int n) {
   if (i == (n-1)) printf(\"\\\"%s         


        
9条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-30 10:52

    OK, here is how to do it in any programming language. I will illustrate it with writing down all the permutations of S4 but one can see easily how in generalizes. One needs to know about special permutations called cycles. The cycle (132) is the permutation that sends 1 to 3, 3 to 2 and 2 back to 1. Think of a numbered circle and one rotates the circle. The cycles (321) and (213) represent the same cycle and permutation. A "two cycle" (13) is a transposition, simply interchanging 1 and 3 and leaving all the other members the same. A "one cycle" (2) sends 2 to 2 and leaves everything else the same, i.e., it does nothing to any element. However, I will write one cycles below to make it look "pretty".

    With that intro, let us start with the set {[1,2,3,4]}. We act on this set by the following sets of cycles:

    The set {(4)}. This does nothing leaving us with

    {[1,2,3,4]}.
    

    We act on this set with the pair of cycles, {(3),(43)}. This gives us

    { [1,2,3,4], [1,2,4,3] }, 
    

    a set with two elements. We act on this second set with the cycles: {(2),(32),(432)}. We have

    (2) { [1,2,3,4], [1,2,4,3] } = { [1,2,3,4], [1,2,4,3] }
    (32) { [1,2,3,4], [1,2,4,3] } = { [1,3,2,4], [1,3,4,2] }
    (432) { [1,2,3,4], [1,2,4,3] } = { [1,4,2,3], [1,4,3,2] }
    

    Writing these out, we have a set of 6 tuples:

    { [1,2,3,4], [1,2,4,3], [1,3,2,4], [1,3,4,2 [1,4,2,3], [1,4,3,2] }
    

    Lastly we hit this set with the cycles {(1),(21),(321),(4321)}. This will give us 24 tuples which are the 4x6 = 24 permutations of S4 - all in lexicographic order!

提交回复
热议问题