官术网_书友最值得收藏!

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.

主站蜘蛛池模板: 湘西| 房山区| 泰宁县| 西昌市| 陇川县| 榆中县| 雷州市| 济南市| 台安县| 巩留县| 双江| 茂名市| 麻江县| 敦化市| 鹤壁市| 台东县| 丹凤县| 手机| 舟山市| 新余市| 水城县| 巴楚县| 神木县| 工布江达县| 文成县| 宝鸡市| 曲阜市| 固镇县| 平阴县| 股票| 竹北市| 泗水县| 余庆县| 新乐市| 陆河县| 穆棱市| 扶绥县| 称多县| 卢氏县| 苍山县| 北安市|