a few things to guide recursive
tags: learning programming leetcode
content
a few things to guide writing recursive functions
- base case
- the base case determines when the function stops
- more importantly, it determines what the sub-problem returns!
- it’s about breaking down problems to sub-problems
- if there’s still a sub-problem, call itself (the recursive function)
- previous state, current state, next state as function input arguments
- keeping track of the state of the sub-problems
- this is how you shrink the problems
- remember to return back to the call stack (and the original caller of the recursive function), not just the base case
- think “what is the calling function waiting to be returned?”
regarding the last point:
- i wrote something like
def my_recursive(curr, prev) -> something:
if curr is None:
return prev
# do something
my_recursive(curr.next, curr)- took me a while to figure out what’s wrong
- it should be
return my_recursive(curr.next, curr) - otherwise, there’s no
returnother than the base case - if it’s Go, compiler is gonna complain about no return
- but it’s python, None is implicitly return when there’s no
returncase
- it should be