#Coding:utf-8defpermutation (inStr, POS, parentdata):ifLen (inStr) = =0:return ifLen (inStr) = = 1: Print "{"+ InStr +"}" return #Here we need a new buffer to avoid to pollute the other nodes.Buffer =[] Buffer.extend (Parentdata)#Choose the elementbuffer.append (Instr[pos])#get the remnant elements.SUBSTR =Kickchar (INSTR, POS)#got one of the result ifLen (subStr) = = 1: Buffer.extend (SUBSTR)PrintBufferreturn #Here we use the loop to choose other children. forIinchRange (len (SUBSTR)): Permutation (subStr, I, buffer)#a simple method to delete the element we choosedefKickchar (SRC, pos): Srcbuf=[] srcbuf.extend (SRC) srcbuf.pop (POS)returnSrcbufdefMain (): Input= ['A','B','C','D'] forIinchRange (len (input)): permutation (input, I, []) main ()
Output:
C:\Python27\python.exe d:/work/search/3.py[' A ', ' B ', ' C ', ' d ' [' A ', ' B ', ' d ', ' C '] [' A ', ' C ', ' B ', ' d ' [' A ', ' C ', ' d ', ' B '] [' A ', ' D ', ' B ', ' C '] [' A ', ' D ', ' C ', ' B '] [' B ', ' A ', ' C ', ' D '] [' B ', ' A ', ' D ', ' C '] [' B ', ' C ', ' A ', ' D '] [' B ', ' C ', ' D ', ' A '] [' B ', ' D ', ' A ', ' C '] [' B ', ' D ', ' C ', ' A '] [' C ', ' A ', ' B ', ' D '] [' C ', ' A ', ' D ', ' B '] [' C ', ' B ', ' A ', ' D '] [' C ', ' B ', ' D ', ' A '] [' C ', ' D ', ' A ', ' B '] [' C ', ' D ', ' B ', ' A '] [' D ', ' A ', ' B ', ' C '] [' D ', ' A ', ' C ', ' B '] [' D ', ' B ', ' A ', ' C '] [' D ', ' B ', ' C ', ' A '] [' D ', ' C ', ' A ', ' B '] [' D ', ' C ', ' B ', ' A '] Process finished with exit code 0
Code borrowed from http://airu.iteye.com/blog/1930391 Java code
Use Python for full alignment