Recursion is when a function calls itself. This requires at least O(n) memory usage for the stack storing the function calls. Here is a great explanation of stack usage in recursive functions.
def factorial(n):
if n <= 1:
return 1
return n * factorial(n - 1)
Memoization is often useful in recursion. This is when the results of a function call are remembered so they can be used again in later function calls. This is like caching your results to use again.
factorial_memo = {}
def factorial(n):
if n <= 1:
return 1
elif n not in factorial_memo:
factorial_memo[n] = n * factorial(n-1)
return factorial_memo[n]
Tail recursion is where calculations are performed first and then the recursive call is executed. Some programming languages, usually functional ones, optimize tail calls so they take up less room on the call stack.
def factorial(n, running_total=1):
if n <= 1:
return running_total
return factorial(n-1, n * running_total)
*My solution was not recursive, but this is a typical recursion problem