给定字符串,如”ABC”,求其全排列。
我是用递归的方式去写的, 思想是,先固定住A, 求BC的全排列,再与A组合,然后再固定住B,求AC的,再固定住C求AB的。
这样递归下去。
python代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
# 全排列 # string 要求的全排列的字符串 # pre_str 用来记录当前要求的string,前面的字符串是什么 # container 用来存储产生的全排列数据 def permutation(string, pre_str, container): if len(string) == 1: # 如不需要容器,此处可以直接打印 container.append(pre_str + string) for idx, str in enumerate(string): # 新的字符串为剥离当前字符串后组成的字符串 new_str = string[:idx] + string[idx+1:] new_pre_str = pre_str + str # 递归往下一层遍历 permutation(new_str, new_pre_str, container) if __name__ == "__main__": container = [] string = "ABC" permutation(string, "", container) print(container) #['ABC', 'ACB', 'BAC', 'BCA', 'CAB', 'CBA'] |
转载文章,版权归作者所有,转载请联系作者。作者:,来源: