exercises---recursion
exercises---recursion
The "work toward base case" is where we make the problem simpler.
The recursive call, is where we use the same algorithm to solve a simpler version of
the problem.
The base case is the solution to the "simplest" possible problem (For example, the
base case to adding a list of numbers would be if the list had only one number... thus
the answer is the number).
rec(N)
if (N<=0)
return 8
else
return N + rec(N-2)
end if
rec(N)
if (N<=1)
return N+1
else
return N * rec(N-3)
end if
rec(N)
if (n>10)
return N - 3;
else
return N + rec(N +2)
end if
rec(N)
if (n > 10)
return n - 1
else
n = n + 1
return N + rec(N + 1)
end if
rec(N)
if (N = = 2)
return 50
else if (N = = 3)
return 100
else
return (rec(N - 1) + rec(N - 2)*2)
end if
7. Which of the following is correct about recursion? Choose all that apply.
9. Consider the following method Anagrams. It is used to print out all the possible
anagrams of a word. The method substring allows extracts to be made from an
alphanumeric variable by passing the positions of in the variable to act as the points
of extraction.
1 Anagrams(PREFIX, WORD)
2 if(WORD.length() <= 1)
3 PRINT(PREFIX + WORD)
4 else
5 loop X from 0 to WORD.length()
6 CUR = WORD.substring(i, i + 1)
7 BEFORE = WORD.substring(0, i) // letters before cur
8 AFTER = WORD.substring(i + 1) // letters after cur
9 Anagrams(PREFIX + CUR, BEFORE + AFTER)
10 end loop
11 end if