So, allow me to ramble on in an unstructured form with the idea of capturing the different types of cannonical recursion examples. When you hear beknighted C++ developers talk, much is made of multiple inheiritance or recursion. Yet, on a daily basis neither really comes up too frequently. The latter, however, when it does appear, usually is the ONLY way to solve some problem. Before I attmpt to topologically capture which recursion problems can be solved with which idioms, I want to consider the mathematical foundations behind a recursion. How many people have an intuitive notion for the running time of Insertion sort without having to the formal inductive proof? Who wants to continue this expansion?
Need idiomatic recursion examples for:
- Exhaustive Permutation
- Exhaustive Subset
- Recursive Backtracking
- Others???
I have only Julie Zelenski at Stanford to thank for any of the following 2 C++ code examples:
1. Exhaustive Permutation example
void RecPermute(string soFar, string rest)
{
if (rest.empty()) {
cout << soFar << endl;
} else {
for (int i = 0; i < rest.length(); i++) {
string remaining = rest.substr(0, i)
+ rest.substr(i+1);
RecPermute(soFar + rest[i], remaining);
}
}
}
2. Exhaustive Subset example
void RecSubsets(string soFar, string rest)
{
if (rest.empty())
cout << soFar << endl;
else {
RecSubsets(soFar + rest[0], rest.substr(1)); // include first char
RecSubsets(soFar, rest.substr(1)); // exclude first char
}
}
Chad Salinas
Filed under: C++ Recursion Idioms | Tagged: Chad Salinas Canoncial Recursion Examples | Leave a Comment »
