Justin's Words

全排列(Permutation)

全排列,比如“123”,全排列即是“123”、“132”、“213”、“231”、“312”、“321”。

Python 实现:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
def permutation(foo):
if foo is None:
return

arr = list(foo)
def allRange(arr, start = 0, length = len(arr)):
if start is length - 1:
print('' . join(arr))
for i in range(start, length):
[arr[start], arr[i]] = [arr[i], arr[start]]
allRange(arr, start + 1)
[arr[start], arr[i]] = [arr[i], arr[start]]

allRange(arr)