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

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.

主站蜘蛛池模板: 莱西市| 巴彦淖尔市| 新安县| 娱乐| 平罗县| 富裕县| 顺义区| 博白县| 成武县| 古浪县| 婺源县| 偏关县| 保康县| 绵阳市| 六枝特区| 南汇区| 蚌埠市| 威远县| 柯坪县| 咸阳市| 静安区| 高密市| 原阳县| 潜江市| 新宁县| 扶沟县| 余干县| 吴川市| 汝南县| 泰兴市| 中阳县| 三门县| 乐亭县| 萨嘎县| 乐亭县| 潼南县| 天长市| 彰化市| 聂荣县| 诏安县| 寻甸|