输出一个字符串的全排列

代码:

# using python3  不考虑有重复的

def permutation(str, begin, length):
    if begin == (length - 1):
        # print("print: begin:%d length:%d" % (begin,length))
        print(str)        #输出一个字符串的全排列
        return

    for i in range(begin,length):
        # print("----i:%d begin:%d length:%d" % (i,begin,length))
        # print("swap1")
        swap(str, begin, i)
        permutation(str, begin + 1, length)
        # print("swap2")
        swap(str, begin, i)

# 交换
def swap(str, begin, i):
    # print("swap: begin:%d i:%d" % (begin,i))
    temp = str[begin]
    str[begin] = str[i]
    str[i] = temp

if __name__ == '__main__':
    str = 'abc'
    str = list(str)
    permutation(str, 0, len(str))

执行结果:

>>> 
=========== RESTART: C:/Users/Administrator/Desktop/permutation.py ===========
['a', 'b', 'c']
['a', 'c', 'b']
['b', 'a', 'c']
['b', 'c', 'a']
['c', 'b', 'a']
['c', 'a', 'b']
>>> 

总结:

第一步,确定首个元素(第一个位置与后边的所有字符进行交换:for循环第一次确定为a,第二次确定为b,第三次确定为c)

第二步,就是对除了第一个位置的后边所有位置的字符进行相同处理,直至剩下一个字符

(注意,swap 交换过后,还是交换回来)

# 打印4个字母的字符串“abcd”
>>> 
=========== RESTART: C:\Users\Administrator\Desktop\permutation.py ===========
## 固定 ‘a’
# 固定 ‘b’
['a', 'b', 'c', 'd']       
['a', 'b', 'd', 'c']
# 固定 ‘c’
['a', 'c', 'b', 'd']
['a', 'c', 'd', 'b']
# 固定 ‘d’
['a', 'd', 'c', 'b']
['a', 'd', 'b', 'c']
## 固定 ‘b’
# 固定 ‘a’
['b', 'a', 'c', 'd']
['b', 'a', 'd', 'c']
# 固定 ‘c’
['b', 'c', 'a', 'd']
['b', 'c', 'd', 'a']
# 固定 ‘d’
['b', 'd', 'c', 'a']
['b', 'd', 'a', 'c']

['c', 'b', 'a', 'd']
['c', 'b', 'd', 'a']
['c', 'a', 'b', 'd']
['c', 'a', 'd', 'b']
['c', 'd', 'a', 'b']
['c', 'd', 'b', 'a']
['d', 'b', 'c', 'a']
['d', 'b', 'a', 'c']
['d', 'c', 'b', 'a']
['d', 'c', 'a', 'b']
['d', 'a', 'c', 'b']
['d', 'a', 'b', 'c']
>>> 

 

reference:

https://www.cnblogs.com/xudong-bupt/p/3200658.html

https://blog.csdn.net/xkx_1223_xkx/article/details/78002186

剑指offer系列之二十六:输出字符串的全排列

https://yq.aliyun.com/articles/14476

你可能感兴趣的:(Python,算法)