Difference between backtracking and recursion?

前端 未结 7 505
长发绾君心
长发绾君心 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:28

    Recursion describes the calling of the same function that you are in. The typical example of a recursive function is the factorial, i.e. something like

    int fact(int n) {
        int result;
        if(n==1) return 1;
        result = fact(n-1) * n;
        return result;
    }
    

    What you see here is that fact calls itself. This is what is called recursion. You always need a condition that makes recursion stop. Here it is if(n==1) combined with the fact that n will always decrease each time it is called (fact(n-1))

    Backtracking is an algorithm that tries to find a solution given parameters. It builds candidates for the solution and abandons those which cannot fulfill the conditions. A typical example for a task to solve would be the Eight Queens Puzzle. Backtracking is also commonly used within Neuronal Networks.

    The program you described uses recursion. Similar to the factorial function, it decreases the argument by 1 and ends if n<1 (because then it will print ar instead of doing the rest).

提交回复
热议问题