字符串的全排列

假定字符串S,以字符序列a1a2...an表示。例如: 对于字符串"abc", 全排列为cba bca bac cab acb abc

本文采用非递归方法给出Python代码实现。

实现的思路采用从特殊到一般的方法(PS: 我的高中数学老师Mr Xie最为推崇的数学方法就是"从特殊到一般,再从一般到特殊")

  • n = 1, 全排列为a1
  • n = 2, 全排列为a1a2, a2a1
  • n = 3, 全排列为a3a1a2, a3a2a1, a1a3a2, a2a3a1, a1a2a3, a2a1a3
  • ...
  • 对于n个字符序列的全排列,是在n-1的全排列的基础上,对每一个字符序列E插入an。插入的方法用伪代码表示为:
for i in [0, 1, ..., N]:        # N为字符序列E的长度     
    e = E[0:i] + an + E[i:]
    
"""
Here is an example to help to understand how E[0:i] and E[i:] work,
    >>> E = "abc"
    >>> l1= [E[0:0], E[0:1], E[0:2], E[0:3]]
    >>> l2= [E[0:],  E[1:],  E[2:],  E[3:]]
    >>> l1
    ['', 'a', 'ab', 'abc']
    >>> l2
    ['abc', 'bc', 'c', '']
    
So, (a) If i == 0, e = an + E
    (b) If i == N, e = E  + an
"""

o Python代码实现

 1 #!/usr/bin/python
 2 import sys
 3 
 4 def str2listuniq(s):
 5     l = []
 6     for c in list(s):
 7         if c not in l:
 8             l.append(c)
 9     return l
10 
11 def insert_c2s(s, c):
12     l = []
13     i = 0
14     while i <= len(s):
15         start = s[0:i]
16         end   = s[i:]
17         e     = start + c + end
18         l.append(e)
19         i += 1
20     return l
21 
22 def list2allperms(l):
23     l_final = [l[0]]
24     for c in l[1:]:
25         l_cell = []
26         for s in l_final:
27             l_cell.extend(insert_c2s(s, c))
28         l_final = l_cell
29     return l_final
30 
31 def main(argc, argv):
32     if argc != 2:
33         sys.stderr.write("Usage: %s <string>
" % argv[0])
34         sys.stderr.write(" e.g.: %s "abc"
" % argv[0])
35         return -1
36 
37     if len(argv[1]) == 0:
38         sys.stderr.write("Oops, string is blank
")
39         return -1
40 
41     l_input = str2listuniq(argv[1])
42     l_final = list2allperms(l_input)
43     if len(l_final) <= 24:
44         print ' '.join(l_final)
45     else:
46         print ' '.join(l_final[0:5]) + " ... " + l_final[-1]
47     print "
The total number of all permutation is %d" % len(l_final)
48 
49     return 0
50 
51 if __name__ == '__main__':
52     argc, argv = len(sys.argv), sys.argv
53     sys.exit(main(argc, argv))

测试结果:

$ ./foo.py a
a

The total number of all permutation is 1

$ ./foo.py ab
ba ab

The total number of all permutation is 2

$ ./foo.py abc
cba bca bac cab acb abc

The total number of all permutation is 6

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

The total number of all permutation is 24

$ ./foo.py abcde
edcba decba dceba dcbea dcbae ... abcde

The total number of all permutation is 120

用C代码实现比较复杂一些,因为要构造动态数组,wait ...

原文地址:https://www.cnblogs.com/idorax/p/6391978.html