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)

 

arrow
arrow
    全站熱搜
    創作者介紹
    創作者 g0d2 的頭像
    g0d2

    kazi1@的部落格

    g0d2 發表在 痞客邦 留言(0) 人氣()