Backtracking lists possibilities one at a time. Some questions don’t need the list, though. They ask how many possibilities there are, or which one is the best, and the number of possibilities can be astronomically large. Dynamic programming answers those questions by noticing that the same smaller question comes up again and again, answering it once, and reusing the answer.
Spot the Repeated Question
Say a basketball team scores only two-point and three-point baskets. How many different sequences of baskets reach exactly 50 points? The last basket was worth 2 or 3, so the answer for 50 is the answer for 48 plus the answer for 47. That rule turns straight into recursion:
let calls = 0;
function sequences(points) {
calls++;
if (points === 0) return 1;
if (points < 0) return 0;
return sequences(points - 2) + sequences(points - 3);
}
console.log(sequences(50), `${calls} calls`);
The answer is right, but the call count gives the problem away:
525456 3236383 calls