回溯(Backtracking)是递归的一种形式,首先,无涯教程要选择一个选项并从中回溯,如果得出的结论是,该特定选项未提供所需的解决方案,则从该选项中回溯。通过遍历每个可用选项来重复这些步骤,直到获得所需的解决方案。
以下是查找给定字母集的所有可能排列顺序的示例。当选择一对时应用回溯来验证是否已经创建,如果尚未创建则该对将添加到答案列表否则将被忽略。
def permute(list, s): if list == 1: return s else: return [ y + x for y in permute(1, s) for x in permute(list - 1, s) ] print(permute(1, ["a","b","c"])) print(permute(2, ["a","b","c"]))
执行以上代码后,将产生以下输出-
链接:https://www.learnfk.comhttps://www.learnfk.com/python-data-structure/python-backtracking.html
来源:LearnFk无涯教程网
['a', 'b', 'c'] ['aa', 'ab', 'ac', 'ba', 'bb', 'bc', 'ca', 'cb', 'cc']
祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)