search
HomeWeb Front-endJS TutorialDetailed explanation of the use of JS dynamic programming

Detailed explanation of the use of JS dynamic programming

Apr 14, 2018 pm 01:56 PM
javascriptusedynamic programming

This time I will bring you a detailed explanation of the use of JS dynamic programming. What are the precautions when using JS dynamic programming? Here are practical cases, let’s take a look.

In fact, in our front-end development, there are not many advanced algorithms used. In most cases, if statements, for statements, swith statements, etc. can be solved . If it's a little more complicated, you might think of using recursion to solve it.

But it should be noted that recursion is simple to write, but in fact it is not very efficient in execution.

Let’s look at the dynamic programming algorithm again:

Dynamic programming solutions start at the bottom, solving all the small problems, and then combine them into a holistic solution to solve the entire big problem.

Example (Calculating Fibonacci Sequence)

The Fibonacci sequence refers to a sequence of numbers 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181, 6765 ,10946,17711,28657,46368.....

This sequence starts with item 3, and each item is equal to the sum of the previous two items.

For this sequence, you can use a recursive function to calculate the nth item value

// 斐波那契数列
function recurFib(n) {
    if(n ");
      return recurFib(n-1)+recurFib(n-2)
    }
}

It is indeed a very concise code. The commented code above is used to print out how many times the function needs to be executed when n =. However, a discerning person can see at a glance that the number of executions will increase as n increases. Very scary growth.

Detailed explanation of the use of JS dynamic programming

When n=5, the recursion tree has grown very big... It can be predicted that when n=10, or even n=100...

After understanding the difference in execution efficiency of recursive functions, let’s look at how dynamic programming is done

function dynFib(n) {
  let val = [];
  for(let i = 0; i <p style="text-align: left;">
The intermediate result is saved in the array val. If the Fibonacci number to be calculated is 1 or 2, then the if statement will return 1. Otherwise, the values ​​1 and 2 will be stored at positions 1 and 2 in the val array. </p><p style="text-align: left;">
The loop will traverse from 3 to the input parameters, and assign each element of the array to the sum of the first two elements. When the loop ends, the last element value of the array is the final calculated Fibonacci value. This value will also be used as the return value <a href="http://www.php.cn/code/6029.html" target="_blank"> of the </a> function. </p><p style="text-align: left;">
Next, you can write a simple test function to compare the running time of the two. </p><pre class="brush:php;toolbar:false">// 定义一个测试函数,将待测函数作为参数传入
function test(func,n){
  let start = new Date().getTime();//起始时间
  let res = func(n);//执行待测函数
  document.write('<br>'+'当n='+n+'的时候 '+res+'<br>');
  let end = new Date().getTime();//结束时间
  return (end - start)+"ms";//返回函数执行需要时间
}

Print function execution

let time = test(recurFib,40);
document.write(time);
let time2 = test(dynFib,40);
document.write(time2);

The results are as follows:

Detailed explanation of the use of JS dynamic programming

Finally, you may have realized that it is possible to calculate the Fibonacci sequence without using arrays when using an iterative approach.

The reason why arrays are needed is because dynamic programming algorithms usually need to save intermediate results.

The following is the iterative version of the Fibonacci function meaning

function iterFib(n) {
  let last = 1;
  let nextLast = 1;
  let result = 1;
  for (let i = 2; i <p style="text-align: left;">
Of course, the efficiency of this iterative version is the same as that of the array version. </p><p> I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the php Chinese website! </p><p>Recommended reading:</p><p><a href="http://www.php.cn/js-tutorial-392657.html" target="_blank">How to use Angular4 input and output</a><br></p><p><a href="http://www.php.cn/js-tutorial-392661.html" target="_blank">How to operate user permissions in Vue2.0</a><br></p><p style="text-align: left;">
</p><!--content end-->

The above is the detailed content of Detailed explanation of the use of JS dynamic programming. For more information, please follow other related articles on the PHP Chinese website!

Statement
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
Javascript Data Types : Is there any difference between Browser and NodeJs?Javascript Data Types : Is there any difference between Browser and NodeJs?May 14, 2025 am 12:15 AM

JavaScript core data types are consistent in browsers and Node.js, but are handled differently from the extra types. 1) The global object is window in the browser and global in Node.js. 2) Node.js' unique Buffer object, used to process binary data. 3) There are also differences in performance and time processing, and the code needs to be adjusted according to the environment.

JavaScript Comments: A Guide to Using // and /* */JavaScript Comments: A Guide to Using // and /* */May 13, 2025 pm 03:49 PM

JavaScriptusestwotypesofcomments:single-line(//)andmulti-line(//).1)Use//forquicknotesorsingle-lineexplanations.2)Use//forlongerexplanationsorcommentingoutblocksofcode.Commentsshouldexplainthe'why',notthe'what',andbeplacedabovetherelevantcodeforclari

Python vs. JavaScript: A Comparative Analysis for DevelopersPython vs. JavaScript: A Comparative Analysis for DevelopersMay 09, 2025 am 12:22 AM

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Python vs. JavaScript: Choosing the Right Tool for the JobPython vs. JavaScript: Choosing the Right Tool for the JobMay 08, 2025 am 12:10 AM

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

See all articles

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment