- Python Data Structures and Algorithms
- Benjamin Baka
- 231字
- 2021-07-09 19:45:07
Backtracking
Backtracking is a form of recursion that is particularly useful for types of problems such as traversing tree structures, where we are presented with a number of options at each node, from which we must choose one. Subsequently we are presented with a different set of options, and depending on the series of choices made either a goal state or a dead end is reached. If it is the latter, we must backtrack to a previous node and traverse a different branch. Backtracking is a divide and conquer method for exhaustive search. Importantly backtracking prunes branches that cannot give a result.
An example of back tracking is given in the following example. Here, we have used a recursive approach to generating all the possible permutations of a given string, s, of a given length n:
def bitStr(n, s):
if n == 1: return s
return [ digit + bits for digit in bitStr(1,s)for bits in bitStr(n - 1,s)]
print (bitStr(3,'abc'))
This generates the following output:

Notice the double list compression and the two recursive calls within this comprehension. This recursively concatenates each element of the initial sequence, returned when n = 1, with each element of the string generated in the previous recursive call. In this sense it is backtracking to uncover previously ingenerated combinations. The final string that is returned is all n letter combinations of the initial string.
- 大學計算機基礎(第三版)
- NativeScript for Angular Mobile Development
- Learning Informatica PowerCenter 10.x(Second Edition)
- Python進階編程:編寫更高效、優雅的Python代碼
- Mastering LibGDX Game Development
- SEO實戰密碼
- 網站構建技術
- RISC-V體系結構編程與實踐(第2版)
- Maker基地嘉年華:玩轉樂動魔盒學Scratch
- SQL Server 入門很輕松(微課超值版)
- Java并發編程:核心方法與框架
- C++ System Programming Cookbook
- 從零開始構建深度前饋神經網絡:Python+TensorFlow 2.x
- C# 7.0本質論
- SCRATCH編程課:我的游戲我做主