Dynamic programming
Divide and conquer, dynamic programming and backtracking all split a problem, but differently. Divide and conquer splits into independent subproblems and combines their solutions. Dynamic programming also splits, but its subproblems depend on one another and repeat a lot. Backtracking tries every sequence of choices and undoes the ones that fail. In Fibonacci of 30, subproblems repeat over 1 million times: that is dynamic programming territory.
Dynamic programming works because the problems have no aftereffect: given a state, what can happen next depends only on that state, not on how it was reached. In stair climbing, from stair i you can go to i + 1 or i + 2, no matter which stairs you landed on before. Whether you went through 2 or 1 to reach 3, from 3 the options are the same.
If the rule Β«you cannot climb 1 stair twice in a rowΒ» is added, state i is no longer enough: if the last move was 1, the next must be 2. A 3-stair staircase can be climbed in 2 ways, because 1 + 1 + 1 is out. The fix is to extend the state: [i, j] is being on stair i with a last move of j. Then: dp[i, 1] = dp[i β 1, 2] and dp[i, 2] = dp[i β 2, 1] + dp[i β 2, 2].
Some problems depend on the whole past. If every time you land on stair i an obstacle appears on 2i, each move changes what can be done later: landing on 2 and 3 blocks 4 and 6. No small state sums all that up, and dynamic programming usually fails. It happens in problems like the traveling salesperson. For them, heuristic search, genetic algorithms or reinforcement learning are used, which find a good solution in reasonable time.
