How to realize dynamic programming
This article introduces the relevant knowledge of "how to achieve dynamic planning". In the operation of actual cases, many people will encounter such a dilemma. Next, let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!
Case 1
Q: given a m x n grid containing non-negative integers, find a path from the upper left corner to the lower right corner so that the sum of numbers on the path is minimized, where arr [m] [n] represents a specific value. You can only move down or to the right one step at a time.
Thinking
Let's go through the relevant steps in turn:
Hongmeng official Strategic Cooperation to build HarmonyOS Technology Community
Define variables: when we define the path sum from the upper left corner to (I, j), the smallest path sum is dp [I -] [j-1]. So, DP [m-1] [nmur1] is the answer we want.
Find the relation: dp [I] [j] = min (DP [I-1] [j], dp [I] [JLV 1]) + arr [I] [j]; arr [I] [j] represents the numerical value in the grid, and the minimum path to the current grid is equal to the smaller path on the left or above plus the value of the grid itself.
Define the initial value: DP [I] [0] = DP [I-1] [0] + arr [I] [0]; dp [0] [I] = dp [0] [Imur1] + arr [0] [I]; the first row or column is the sum of the whole row and column.
Coding
As you can imagine from the above analysis, then we need to implement it in code. For the records that need to be used before, we can consider using a two-dimensional array to record them, so we have the following code.
Public int dp (int [] [] arr) {int m = arr.length; int n = arr [0] .length; if (m