以下代码生成字符串的所有排列:
def permutations(word):
if len(word)<=1:
return [word]
#get all permutations of length N-1
perms=permutations(word[1:])
char=word[0]
result=[]
#iterate over all permutations of length N-1
for perm in perms:
#insert the character into every possible location
for i in range(len(perm)+1):
result.append(perm[:i] + char + perm[i:])
return result
你能解释一下它是如何工作的吗?我不明白递归。
答案 0 :(得分:53)
算法是:
递归的基本案例是单个字母。只有一种方法可以置换一封信。
工作示例
想象一下,起始单词是bar
。
b
。ar
的缩写。这会提供ar
和ra
。b
放在每个位置:
ar
- &gt; bar
,abr
,arb
ra
- &gt; bra
,rba
,rab
答案 1 :(得分:7)
我已经为长度为2的字符串和长度为3的字符串编写了步骤。
<强>置换( 'AB')强>
len('ab') is not <= 1
perms = permutations of 'b'
len('b') <= 1 so return 'b' in a list
perms = ['b']
char = 'a'
result = []
for 'b' in ['b']:
for 0 in [0,1]:
result.append('' + 'a' + 'b')
for 1 in [0,1]:
result.append('b' + 'a' + '')
result = ['ab', 'ba']
<强>置换( 'ABC')强>
len('abc') is not <= 1
perms = permutations('bc')
perms = ['bc','cb']
char = 'a'
result =[]
for 'bc' in ['bc','cb']:
for 0 in [0,1,2]:
result.append('' + 'a' + 'bc')
for 1 in [0,1,2]:
result.append('b' + 'a' + 'c')
for 2 in [0,1,2]:
result.append('bc' + 'a' + '')
for 'cb' in ['bc','cb']:
for 0 in [0,1,2]:
result.append('' + 'a' + 'cb')
for 1 in [0,1,2]:
result.append('c' + 'a' + 'b')
for 2 in [0,1,2]:
result.append('cb' + 'a' + '')
result = ['abc', 'bac', 'bca', 'acb', 'cab', 'cba']