假定字符串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 l10 11 def insert_c2s(s, c):12 l = []13 i = 014 while i <= len(s):15 start = s[0:i]16 end = s[i:]17 e = start + c + end18 l.append(e)19 i += 120 return l21 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_cell29 return l_final30 31 def main(argc, argv):32 if argc != 2:33 sys.stderr.write("Usage: %s\n" % argv[0])34 sys.stderr.write(" e.g.: %s \"abc\"\n" % argv[0])35 return -136 37 if len(argv[1]) == 0:38 sys.stderr.write("Oops, string is blank\n")39 return -140 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 "\nThe total number of all permutation is %d" % len(l_final)48 49 return 050 51 if __name__ == '__main__':52 argc, argv = len(sys.argv), sys.argv53 sys.exit(main(argc, argv))
测试结果:
$ ./foo.py aaThe total number of all permutation is 1$ ./foo.py abba abThe total number of all permutation is 2$ ./foo.py abccba bca bac cab acb abcThe total number of all permutation is 6$ ./foo.py abcddcba cdba cbda cbad dbca bdca bcda bcad dbac bdac badc bacd dcab cdab cadb cabd dacb adcb acdb acbd dabc adbc abdc abcdThe total number of all permutation is 24$ ./foo.py abcdeedcba decba dceba dcbea dcbae ... abcdeThe total number of all permutation is 120
用C代码实现比较复杂一些,因为要构造动态数组,wait ...