Difference between backtracking and recursion?

前端 未结 7 486
长发绾君心
长发绾君心 2021-01-30 01:47

What is the difference between backtracking and recursion? How is this program working?

void generate_all(int n)
{
    if(n<1) printf("%s\\n", ar);
         


        
相关标签:
7条回答
  • 2021-01-30 02:38

    That question is like asking what's the difference between a car and a DeLorean.

    In recursion function calls itself until reaches a base case.

    In backtracking you use recursion in order to explore all the possibilities until you get the best result for the problem.

    Can be a bit hard to understand, I attach some text from here:

    "Conceptually, you start at the root of a tree; the tree probably has some good leaves and some bad leaves, though it may be that the leaves are all good or all bad. You want to get to a good leaf. At each node, beginning with the root, you choose one of its children to move to, and you keep this up until you get to a leaf.

    Suppose you get to a bad leaf. You can backtrack to continue the search for a good leaf by revoking your most recent choice, and trying out the next option in that set of options. If you run out of options, revoke the choice that got you here, and try another choice at that node. If you end up at the root with no options left, there are no good leaves to be found."

    This needs an example:

    Tree with bad nodes and one good node

    Your piece of code is simply recursion, as you never get back if the result doesn't fit your goal.

    0 讨论(0)
提交回复
热议问题