gpt4 book ai didi

python - 回溯时如何存储递归结果?

转载 作者:行者123 更新时间:2023-12-01 09:28:33 24 4
gpt4 key购买 nike

我目前正在学习通过递归生成排列。

我发现以下代码非常适合打印排列,但我似乎无法存储这些值:堆栈中的所有值在升级时都会丢失。

def permute_util(str, count, result, level):

if level == len(result):
print(result)
return

for i in range(len(str)):
if count[i] == 0:
continue;
result[level] = str[i]
count[i] -= 1
permute_util(str, count, result, level + 1)
count[i] += 1

permute_util(list("ABC"), [2,1,1], [None]*len("AABC"), 0)
<小时/>

结果:

['A', 'A', 'B', 'C']
['A', 'A', 'C', 'B']
['A', 'B', 'A', 'C']
['A', 'B', 'C', 'A']
['A', 'C', 'A', 'B']
['A', 'C', 'B', 'A']
['B', 'A', 'A', 'C']
['B', 'A', 'C', 'A']
['B', 'C', 'A', 'A']
['C', 'A', 'A', 'B']
['C', 'A', 'B', 'A']
['C', 'B', 'A', 'A']
<小时/>

我尝试在基本情况下将结果添加到全局列表中,但只有最新级别才会被存储,而所有其他以前的值都会被覆盖,就像这样

 def permute_util(str, count, result, level):
global glob
if level == len(result):
**glob += [result]**
return

for i in range(len(str)):
if count[i] == 0:
continue;
result[level] = str[i]
count[i] -= 1
permute_util(str, count, result, level + 1)
count[i] += 1

permute_util(list("ABC"), [2,1,1], [None]*len("AABC"), 0)

['C', 'B', 'A', 'A']
['C', 'B', 'A', 'A']
['C', 'B', 'A', 'A']
['C', 'B', 'A', 'A']
['C', 'B', 'A', 'A']
['C', 'B', 'A', 'A']
['C', 'B', 'A', 'A']
['C', 'B', 'A', 'A']
['C', 'B', 'A', 'A']
['C', 'B', 'A', 'A']
['C', 'B', 'A', 'A']
['C', 'B', 'A', 'A']
['C', 'B', 'A', 'A']

也尝试了同样的效果:

 def permute_util(str, count, result, level, lists):
global glob
if level == len(result):
return [result]


for i in range(len(str)):
if count[i] == 0:
continue;
result[level] = str[i]
count[i] -= 1
foo = permute_util(str, count, result, level + 1, lists)
lists = lists + foo
count[i] += 1

lists = []
permute_util(list("ABC"), [2,1,1], [None]*len("AABC"), 0, lists)

将基本情况中的所有“结果”存储在列表中并在完成时返回它的最佳方法是什么?

最佳答案

随着递归的进行,您会一遍又一遍地改变结果。
你可以这样做:

def permute_util(string, count, result, level):

if level == len(result):
print(result)
res.append(tuple(result)) # stores current result as a copy in an immutable tuple
return

for i in range(len(string)):
if count[i] == 0:
continue;
result[level] = string[i]
count[i] -= 1
permute_util(string, count, result, level + 1)
count[i] += 1


if __name__ == '__main__':

res = []

permute_util(list("ABC"), [2, 1, 1], [None]*len("AABC"), 0)
print(res)

关于python - 回溯时如何存储递归结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50146993/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com