Table of Contents
Concept
Basic idea
Method 1: Recursive solution
Method 2: Memo Algorithm
This is just one of the simplest questions in dynamic programming, because it has only one change dimension
Home Web Front-end JS Tutorial Detailed case explanation: Introduction to dynamic programming (taking stairs as an example)

Detailed case explanation: Introduction to dynamic programming (taking stairs as an example)

Aug 09, 2018 pm 04:33 PM
javascript

Concept

Dynamic programming (dynamic programming) is a branch of operations research and a mathematical method for optimizing the decision process.
Dynamic programming algorithms are usually based on a recursion formula and one or more initial states. The solution to the current subproblem will be derived from the solution to the previous subproblem .

Basic idea

To solve a given problem, we need to solve its different parts (i.e.solve subproblems), and then combine the solutions of the subproblems to get Solution to the original problem.
Usually many sub-problems are very similar, so the dynamic programming method tries to only solve each sub-problem once , thereby reducing the amount of calculation.
Once the solution to a given sub-problem has been calculated, it is memorized and stored so that the next time the solution to the same sub-problem is needed, the table can be directly looked up.
This approach is particularly useful when the number of repeated subproblems grows exponentially with the size of the input.
Dynamic programming has three core elements:
1. Optimal substructure
2. Boundary
3. State transition equation

Let’s take a look at the question

There is a staircase with a height of 10 steps. Walking from bottom to top, each step can only go up 1 or 2 steps. Find how many moves there are in total.

For example, taking one step at a time, taking a total of 10 steps, is one of the walking methods.
For another example, take 2 steps each time, taking a total of 5 steps. This is another way of walking.

But it’s too troublesome to calculate each step like this. We can just think about how to take the last step, as shown below
Detailed case explanation: Introduction to dynamic programming (taking stairs as an example)

How to get to the tenth staircase= Go to the eighth stair and go to the ninth stair
We use f(n) to represent the way to go to the nth stair, so we have f(10) = f(9) f(8)
Then f(9) = f(8) f(7), f(8) = f(7) f(6)......

In this way we will get aRecursive formula:
f(n) = f(n-1) f(n-2);
There are also two Initial states
f(1) = 1;
f(2) = 2;

This gives us the first solution

Method 1: Recursive solution

function getWays(n) {

    if (n < 1) return 0;
    if (n == 1) return 1;
    if (n == 2) return 2;

    return getWays(n-1) + getWays(n-2); 
}
Copy after login

The time complexity of this method isO(2^n)
Detailed case explanation: Introduction to dynamic programming (taking stairs as an example)

You can see that this is a binary tree. The number of nodes is the number of times our recursive equation needs to be calculated.
The height of the number is N, and the number of nodes is approximately 2^n
so the time is complicated The degree is approximately O(2^n)

, but can this method be optimized?
We will find that some values ​​are repeatedly calculated, as shown in the figure below
Detailed case explanation: Introduction to dynamic programming (taking stairs as an example)The same color represents the repeated parts, so can we record these repeatedly calculated values?
There is a second method for such optimization

Method 2: Memo Algorithm

const map = new Map(); 
function getWays(n) {

    if (n < 1) return 0;
    if (n == 1) return 1;
    if (n == 2) return 2;

    if (map.has(n)) {
        return map.get(n);
    }
    const value = getWays(n-1) + getWays(n-2);
    map.set(n, value);
    return value; 
}
Copy after login

Because n-2 key-value pairs will eventually be stored in the map , so the space complexity is O(n), and the time complexity is also O(n)

. Keep thinking about it. This is the optimal solution. ?

Let’s go back to the original idea. We assume that the previous stairs have been walked and only consider the last step, so we come to f(n) = f(n-1) f(n-2) The recursive formula of See if it works

This is the number of moves for one and two stairs at the beginning, which is the Detailed case explanation: Introduction to dynamic programming (taking stairs as an example)initial state

# mentioned before ##This is an iteration to get three stairs. f(3) only depends on f(1) and f(2)

Detailed case explanation: Introduction to dynamic programming (taking stairs as an example)Continue to the next step

Here another iteration is performed to obtain the steps of 4 stairs. f(4) only depends on f(2) and f(3)
Detailed case explanation: Introduction to dynamic programming (taking stairs as an example)We find that each iteration only requires the results of the first two iterations. Data, there is no need to save the data of all sub-states like a memo

Method 3: Dynamic programming solution

function getWays(n) {

    if (n < 1) return 0;
    if (n == 1) return 1;
    if (n == 2) return 2;

    // a保存倒数第二个子状态数据,b保存倒数第一个子状态数据, temp 保存当前状态的数据
    let a = 1, b = 2;
    let temp = a + b;
    for (let i = 3; i <= n; i++) {
        temp = a + b;
        a = b;
        b = temp; 
    }
    return temp; 
}
Copy after login
This is where we can look at the current time complexity And space complexity
The current time complexity is still

O(n)
, but the space complexity is reduced toO(1)This is the ideal result
Summary

This is just one of the simplest questions in dynamic programming, because it has only one change dimension

When the change dimensions become two, three or even more, it will be more complicated , the knapsack problem is a typical multi-dimensional problem. If you are interested, you can go online and read "Nine Lectures on Backpacks"

Related recommendations:

Detailed explanation of the use of JS dynamic programming

JavaScript advanced algorithm dynamic programming example analysis

The above is the detailed content of Detailed case explanation: Introduction to dynamic programming (taking stairs as an example). For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to implement an online speech recognition system using WebSocket and JavaScript How to implement an online speech recognition system using WebSocket and JavaScript Dec 17, 2023 pm 02:54 PM

How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: key technologies for implementing real-time monitoring systems WebSocket and JavaScript: key technologies for implementing real-time monitoring systems Dec 17, 2023 pm 05:30 PM

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

How to use JavaScript and WebSocket to implement a real-time online ordering system How to use JavaScript and WebSocket to implement a real-time online ordering system Dec 17, 2023 pm 12:09 PM

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

How to implement an online reservation system using WebSocket and JavaScript How to implement an online reservation system using WebSocket and JavaScript Dec 17, 2023 am 09:39 AM

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

JavaScript and WebSocket: Building an efficient real-time weather forecasting system JavaScript and WebSocket: Building an efficient real-time weather forecasting system Dec 17, 2023 pm 05:13 PM

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

How to use insertBefore in javascript How to use insertBefore in javascript Nov 24, 2023 am 11:56 AM

Usage: In JavaScript, the insertBefore() method is used to insert a new node in the DOM tree. This method requires two parameters: the new node to be inserted and the reference node (that is, the node where the new node will be inserted).

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

JavaScript and WebSocket: Building an efficient real-time image processing system JavaScript and WebSocket: Building an efficient real-time image processing system Dec 17, 2023 am 08:41 AM

JavaScript is a programming language widely used in web development, while WebSocket is a network protocol used for real-time communication. Combining the powerful functions of the two, we can create an efficient real-time image processing system. This article will introduce how to implement this system using JavaScript and WebSocket, and provide specific code examples. First, we need to clarify the requirements and goals of the real-time image processing system. Suppose we have a camera device that can collect real-time image data

See all articles