r/learnprogramming • u/Temporary-Warthog250 • 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
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 tofib(5) + fib(4), which is equal to(fib(4) + fib(3)) + (fib(3) + fib(2)), and so on until the base case wherefib(1)andfib(2)are 1. But notice you're solvingfib(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.