Framework for DP Problems

This framework is applicable to nearly every DP problem and provides a clear step-by-step approach to developing DP algorithms.

Using the problem Climbing Stairs (Leetcode 70) as an example, with a top-down(recursive) implementation.

Before we start, we need to first define a term: state. In a DP problem, a state is a set of variables that can sufficiently describe a scenario. These variables are called state variables, and we only care about relevant ones. For example, to describe every scenario in Climbing Stairs, there is only 1 relevant state variable, the current step we are on. We can denote this with an integer i. If i=6, that means that we are describing the state of being on the 6th step. Every unique value for i represents a unique state.

You might be wondering what ‘relevant’ means here. Picture this problem in real life: you are on a set of stairs, and you want to know how many ways there are to climb to say, the 10th step. We’re definitely interested in what step you’re currently standing on. However, we aren’t interested in what color your socks are. You could certainly include sock color as a state variable. Standing on the 8th step wearing green socks is a different state than standing on the 8th step wearing red socks. However, changing the color of your socks will not change the number of ways to reach the 10th step from your current position. Thus the color of your socks is an irrelevant variable. In terms of figuring out how many ways there are to climb the set of stairs, the only relevant variable is what stair you are currently on.


The Framework

To solve a DP problem, we need to combine 3 things:

  1. A function or data structure that will compute/contain the answer to the problem for every given state.

  2. A recurrence relation to transition between states.

  3. Base cases, so that our recurrence relation doesn’t go on infinitely.

猜你喜欢

转载自blog.csdn.net/BSCHN123/article/details/121868155