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);
else{
ar[n-1]='0'; //fix (n)th bit as '0'
generate_all(n-1); //generate all combinations for other n-1 positions.
ar[n-1]='1'; //fix (n)th bit as '1'
generate_all(n-1); //generate all combinations for other n-1 positions.
}
}
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:
Your piece of code is simply recursion, as you never get back if the result doesn't fit your goal.