r/learnprogramming • • Apr 05 '22

Name one programming/comp sci concept you never understood and if you understand it, try to explain it to them

Name a programming concept such as virtual functions, pointers, certain algorithms, etc that you always had a hard time understanding and why.

Someone else who reads yours and does understand it, try to explain it to them to help them learn

1.6k Upvotes

738 comments sorted by

View all comments

255

u/ICantPCGood Apr 05 '22

Dynamic Programming, it’s just recursion with notes about what you’ve done already?

We covered it in a class with the only teacher I’ve ever truly called “bad” and then every teacher after just assumed we all knew it 🙃. Could never really grok it on my own or figure out how to apply it.

30

u/MyHomeworkAteMyDog Apr 05 '22 edited Apr 05 '22

I think of DP as a bottom up approach while recursion is top down. The typical example is the computation tree of a Fibonacci sequence, Fib(n)=fib(n-1) + fib(n-2). Calling fib(n) this way requires 2n fib() calls, many of which are repeated computations. But with DP, you start bottom up, computing and storing fib(0), fib (1), fib(2), …, fib(n-2), fib(n-1), fib(n) in a table. Each next fib call is solved in constant time, using the values previously stored in your table. This lets us avoid recursively recomputing down to the base case for each fib call. With DP, you start with the base case of the recursion and generate the values up to the starting value. This way you can get an answer to Fibonacci(n) in linear time rather then exponential.

7

u/kupiakos Apr 05 '22

Recursion with memoization would get you the same answer with the same number of fib calls, it's just a different approach

7

u/faceplanted Apr 05 '22

You're missing one detail though, using dynamic programming prevents you blowing the stack trying to get to the very first lead in the tree to memoize it, dynamic programming, what with the way it works upwards and uses iteration doesn't have that problem.

→ More replies (1)