close
A permutation, also called an “arrangement number” or “order,” is a rearrangement of the elements of an ordered list S into a one-to-one correspondence with S itself. A string of length n has n! permutation.
Source: Mathword(http://mathworld.wolfram.com/Permutation.html)
Below are the permutations of string ABC.
ABC, ACB, BAC, BCA, CAB, CBA
Here is a solution using backtracking.
def permutation(sz, pre): if pre == len(sz) - 1: print ''.join(sz) return for x in xrange(pre,len(sz)): sz[pre], sz[x] = sz[x], sz[pre] permutation(sz, pre + 1) sz[pre], sz[x] = sz[x], sz[pre] if __name__ == '__main__': sz = 'abc' permutation(list(sz), 0)
全站熱搜
留言列表