简体   繁体   中英

Understanding Backtracking

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'))

Please explain what is happening in this piece of code. How is backtracking taking place?

This code is hard to understand because of the huge return statement.

Basically, you are recursing in all situations expcept when you reach the termination condition. All backtracking is just depth first search with specific termination conditions.

Consider walking through a maze where for each step you make a decision, that decision is a call to the call stack (which conducts your depth first search)... if you reach the end, you can return your path. However, if you reach a deadend, you want to return out of a certain decision, in essence returning out of a function on your call stack.

So when I think of backtracking I care about

  1. State
  2. Decisions
  3. Base Cases (Termination Conditions)

Whenever we are not at a Base Case we are altering our state by making decisions, we are altering state by making decisions on line 3 in that code and we make decisions towards our termination condition on line 2.

Backtracking is explained pretty well in this video .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM