今天写代码有一块需要将四个数全排列,但是不知道如何把所有结果保存在一个列表中(用的是递归,照传统格式写的)
但是目前只能打印输出,不能保存
def per(pos,lt):
lst = lt
if pos == len(lst)-1:
print(lst)
else:
for index in range(pos,len(lst)):
lst[index],lst[pos] = lst[pos],lst[index]
per(pos+1,lst)
lst[index],lst[pos] = lst[pos],lst[index]
per(0,[1,2,3,4])
[1, 2, 3, 4]
[1, 2, 4, 3]
[1, 3, 2, 4]
[1, 3, 4, 2]
[1, 4, 3, 2]
[1, 4, 2, 3]
[2, 1, 3, 4]
[2, 1, 4, 3]
[2, 3, 1, 4]
[2, 3, 4, 1]
[2, 4, 3, 1]
[2, 4, 1, 3]
[3, 2, 1, 4]
[3, 2, 4, 1]
[3, 1, 2, 4]
[3, 1, 4, 2]
[3, 4, 1, 2]
[3, 4, 2, 1]
[4, 2, 3, 1]
[4, 2, 1, 3]
[4, 3, 2, 1]
[4, 3, 1, 2]
[4, 1, 3, 2]
[4, 1, 2, 3]
我曾尝试加上 listname.append(lst) 但无论放在哪都不对
把结果返回到一个列表变量中
在题主的基础上改一下,仅供参考:
def per(pos,lt,lsts):
lst = lt
if pos == len(lst)-1:
lsts.append(lst.copy())
else:
for index in range(pos,len(lst)):
lst[index],lst[pos] = lst[pos],lst[index]
per(pos+1,lst,lsts)
lst[index],lst[pos] = lst[pos],lst[index]
lsts = []
per(0,[1,2,3,4],lsts)
print(lsts)
nums = [1, 2, 3, 4]
size = len(nums)
ans = []
vis = [0 for x in nums]
def dfs(cur: int, path: List):
if len(path) == size:
ans.append([x for x in path])
return
for idx in range(size):
if 0 == vis[idx]:
path.append(nums[idx])
vis[idx] = 1
dfs(idx, path)
path.pop()
vis[idx] = 0
path_ = []
dfs(0, path_)
print(ans)
全局变量好像也不行,你可以换个方式来遍历,例如