UCLA Recursion
UCLA Recursion
Examples of Recursion
PIC 10B
Todd Wittman
Ex: Palindromes
A palindrome is a word that is the same backwards
and forwards.
eve madam racecar amanaplanacanalpanama
To test for palindrome, we compare 1st & last letter.
Then the 2nd & 2nd to last letter. And so on...
Test with function call:
isPalindrome("madam");
isPalindrome("madam");
Remember booleans are evaluated left to right and a
true/false value is returned as soon as possible.
bool isPalindrome (string s) {
if (s.length
() <= 1) return true;
(s.length()
return (s[0]==s[s.length()(s[0]==s[s.length()-1])
&& isPalindrome(s.substr(1,s.length()isPalindrome(s.substr(1,s.length()-2));
}
firstPart
secondPart
Is firstPart a word in the dictionary?
RECURSION STEP
YES -- Can secondPart be parsed?
YES -- return true and
parsed = firstPart + " " + parsedSecondPart
NO -- Increment position i.
Ex: Permutations
To permute 4 things, fix the first item ("Y") and then permute
the last 3 things ("ODA")
Now fix the first of the 3 things ("O") and permute the
remaining 2 ("DA").
Note there is recursion here.
Ex: Permutations
Sec 14.2:
14.2: We want to generate a string vector
containing all possible permutations of a given word.
So we would call our function permute as below.
int main() {
string word;
cout << "Enter a word: ";
cin >> word;
cout<<"The
cout<<"The permutations of "<<word<<" are:\
are:\n";
vector<string> v = permute(word);
permute(word);
for (int
(int i=0; i < v.size();
v.size(); i++)
cout << v[i]
v[i] << "\
"\n";
return 0;
}
Application: Anagrams