unit 5 - recursion Flashcards
recursion
when a function calls itself
recursion is useful when
something calls for a repeated process with different values / close values, but only returning one value
iterative > recursion for
speed and memory
Recursive > iterative for
keeping track of previous steps
branching path problems
different conditions require different procedures;
recursion is useful for finding the optimal path
Abstract data type best representing recursive function calls
stack
greedy algorithm
takes the step that brings it closest to its goal at every junction
coin counting: greedy algorithm
sort coin values;
for each value, while it is less than the amount of money needed, subtract that value from the amount;
append # of coins for each subtraction operation
downside to greedy algorithms
the biggest step is not always the most efficient;
with arbitrary coins, a coin counting algorithm may not take the most efficient steps. Less coins will be received with a different coin
coin counting: recursive algorithm
if amt in coins: return 1;
validcoins = [c in coins if c < amt];
for coin in valuelist: numcoins = 1 + fewest_coins(amt - coin, coins);
If numcoins < mincoins: mincoins = numcoins
memoization
the practice of storing a subset of solved problems