algorithm - How do lexicographical permutations work algorithmically? -


or example, if given "abcd", lexicographical permutations be:

abcd abdc  acbd acdb  adbc  adcb bacd badc bcad bcda bdac bdca cabd cadb cbad cbda cdab cdba dabc dacb dbac dbca dcab dcba 

i understand intuitively how meant sorted , if gave me set of letters or numbers work out how should sorted, not mathematically of how 1 step next. example: mathematical process takes abdc acbd?

well, 1 option :

to go 1 step next,

  • let p = n-1
  • you take (p)th letter abdc => d.
    • you take next letter according order.
      • if exists, write it, end word remaining letters ordered
      • else, p = p - 1 , go previous step.

not sure best way do. why wanting go 1 step next ? why not writing words, begining writing (n-1)! words begining first letter, (n -1)! second...

a ... b b ... b 

for each 1 of these words : continue (n-2)! second letter , (n-2)! third letter :

ab ab ... ab ac ac .... ac .... ba ba ... bc bc .... 

and on


Comments