Python生成n个元素的全排列
本文将使用Python语言编写程序生成n个元素的全排列,代码不使用第三方库;
生成全排列
def permute(nums):
length = len(nums)
permutations = []
def _permute(index=0):
if index == length:
permutations.append(nums[0:length])
for i in range(index,length):
nums[i],nums[index] = nums[index],nums[i]
_permute(index+1)
nums[i],nums[index] = nums[index],nums[i]
_permute()
return permutations
nums = [i for i in range(1,4)] #[1,2,3]
print("Input:\n",nums)
P = permute(nums)
print("Permutations:")
for p in P:
print(p)
运行效果
Input: [1, 2, 3] Permutations: [1, 2, 3] [1, 3, 2] [2, 1, 3] [2, 3, 1] [3, 2, 1] [3, 1, 2]