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);
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).