Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to realize dynamic programming

2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

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

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report