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

Show parent comments

88

u/AlSweigart Author: ATBS Apr 05 '22

(Heh, I just got done writing an entire book on recursion.)

YEP. Famously, the name "dynamic programming" is meaningless. The guy behind DP named it that because he wanted to do math research for RAND but the Secretary of Defense hated "research" projects and wouldn't fund them. Though other people say this story isn't actually true.

Dynamic programming falls into two categories. The first is, as you noted, just recursion but specifically the kind of recursive problems that have overlapping subproblems. For example, recursive Fibonacci has a problem where you keep solving the same thing over and over again: fib(6) is equal to fib(5) + fib(4), which is equal to (fib(4) + fib(3)) + (fib(3) + fib(2)), and so on until the base case where fib(1) and fib(2) are 1. But notice you're solving fib(3) multiple times. These are the overlapping subproblems. The return value never changes, so why not just use a little memory to remember the calculation after doing it once and just re-use that result? This form of caching is specifically called memoization (not memorization). Dynamic programming is recursive algorithms that use memoization to handle their overlapping subproblems.

Merge sort and quicksort are recursive algorithms, but you don't have any repeat recursive calls there so there are no overlapping subproblems.

The other part of DP is tabulation, which is where you effectively start from the base cases and build up to the big problem you want to solve, storing results in a table in memory to help you solve things. For fibonacci, you're starting from the first two numbers 1 and 1 and building up the the nth number.

These are called "top-down dynamic programming" and "bottom-up dynamic programming". Note that there's no such thing as "top-down recursion" and "bottom-up recursion": all recursion is top-down and "bottom-up" recursive algorithms don't actually have recursive function calls and aren't recursive.

4

u/ICantPCGood Apr 05 '22

Thanks! That’s super helpful. I could recall that there was two approaches but had a hard time distinguishing between them. Also the naming history is good to know because I was definitely trying to read in to the name and figure out what was dynamic about Dynamic Programming which lead to a lot of frustration.

1

u/[deleted] Apr 06 '22 edited Apr 06 '22

Thank you, Sir! Once again you shed a beacon of light.

I plug for you:

The Recursive Book of Recursion

https://nostarch.com/recursive-book-recursion