


Detailed explanation of JS's full arrangement algorithm of strings and memory overflow
This article mainly shares with you JS's full permutation algorithm for strings and detailed explanation of memory overflow. Given a string, find the full permutation of all character combinations in the string. The characters contained are not repeated.
输入:"abc" 输出:["abc","acb","bac","bca","cab","cba"]
I encountered a problem when implementing the algorithm, and I still can't solve it. But the total permutation algorithm is very important, so I wrote this article to record it.
Algorithm 1: Recursive
Algorithm idea:
When the length of the string is 1, output the string;
-
When the length is greater than 1, take the first letter of the string, find the full arrangement of the string with length -1, and insert the first letter into any position of each arrangement.
Algorithm implementation:
function permutate(str) { //保存每一轮递归的排列结果 var result = []; //初始条件:长度为1 if (str.length == 1) { return [str] } else { //求剩余子串的全排列,对每个排列进行遍历 var preResult = permutate(str.slice(1)); for (var j = 0; j < preResult.length; j++) { for (var k = 0; k < preResult[j].length + 1; k++) { //将首字母插入k位置 var temp = preResult[j].slice(0, k) + str[0] + preResult[j].slice(k); result.push(temp); } } return result; } }
The algorithm should not be difficult to understand. However, when the parameter string is "abcdefghijkl"
, the space used for arrangement is 12!=479001600
, and excessive memory usage leads to memory overflow. If you are executing on your own PC, you can use node --max-old-space-size=8192
to modify the memory. But I need to execute on Codewars, so the memory cannot be modified. So my idea was to use tail recursion optimization. Haha, Node’s tail recursion optimization? No matter, let’s try it first.
Algorithm 2: Tail recursion
function permutate(str,result) { 'use strict'; let tempArr = []; //终止条件str长度为0 if (str.length == 0) { return result } else { //第一次递归时,插入首字母 if(result.length === 0){ tempArr.push(str[0]); }else{ for (let i = 0; i < result.length; i++) { let item = result[i]; let itemLen = item.length; for (let j = 0; j < itemLen+1; j++) { let temp = item.slice(0, j) + str[0] + item.slice(j); tempArr.push(temp); } } } //递归截取了第一个字符的子串 return permutate(str.slice(0),tempArr); } } permutate("abcdefghijkl",[]);
The first parameter of the function is the string of this recursion, and the second parameter is the full arrangement result of the first x characters.
The idea is:
Get the first letter of the recursive string each time;
If the length of the second parameter is 0 indicates that it is the first recursion, and the initialization result is
[first letter]
. Then remove the first letter from the recursive string and pass the remaining string to the next recursion;For each subsequent recursion, take the first letter of the recursive string and insert it into the first x characters At all positions of the full arrangement, find the full arrangement of x+1 characters;
-
Recurse until the first parameter is an empty string, then the second parameter is all the characters of the string full arrangement.
It may not be easy to understand, but just know that this is tail recursion. Although tail recursion is only valid in the strict mode of ES6, it still doesn't work after I add
'use strict';
. In fact, I think it is not an overflow of the function call stack, but an overflow of the heap storing variables. So, there is probably no solution. After all, no matter what the full arrangement is, the space complexity is O(n!).
Algorithm 3: Loop
Finally, I’ll post the code for the loop. It’s of no use, so just use it to expand your ideas.
function perm(str) { let result = [],tempArr = []; let subStr = str; while (subStr.length !== 0) { if (result.length === 0) { result.push(str[0]); } else { for (let i = 0; i < result.length; i++) { let item = result[i]; let itemLen = item.length; for (let j = 0; j < itemLen+1; j++) { let temp = item.slice(0, j) + subStr[0] + item.slice(j); tempArr.push(temp); } } result = tempArr; tempArr = []; } subStr = subStr.slice(1); } return result; }
Related recommendations:
JS full permutation and combination algorithm implementation method
Detailed explanation of several recursive full permutation algorithm examples in JavaScript
JavaScript fun question: full arrangement and deduplication
The above is the detailed content of Detailed explanation of JS's full arrangement algorithm of strings and memory overflow. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



For mechanical hard drives or SATA solid-state drives, you will feel the increase in software running speed. If it is an NVME hard drive, you may not feel it. 1. Import the registry into the desktop and create a new text document, copy and paste the following content, save it as 1.reg, then right-click to merge and restart the computer. WindowsRegistryEditorVersion5.00[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SessionManager\MemoryManagement]"DisablePagingExecutive"=d

According to news from this website on September 3, Korean media etnews reported yesterday (local time) that Samsung Electronics and SK Hynix’s “HBM-like” stacked structure mobile memory products will be commercialized after 2026. Sources said that the two Korean memory giants regard stacked mobile memory as an important source of future revenue and plan to expand "HBM-like memory" to smartphones, tablets and laptops to provide power for end-side AI. According to previous reports on this site, Samsung Electronics’ product is called LPWide I/O memory, and SK Hynix calls this technology VFO. The two companies have used roughly the same technical route, which is to combine fan-out packaging and vertical channels. Samsung Electronics’ LPWide I/O memory has a bit width of 512

According to the report, Samsung Electronics executive Dae Woo Kim said that at the 2024 Korean Microelectronics and Packaging Society Annual Meeting, Samsung Electronics will complete the verification of the 16-layer hybrid bonding HBM memory technology. It is reported that this technology has passed technical verification. The report also stated that this technical verification will lay the foundation for the development of the memory market in the next few years. DaeWooKim said that Samsung Electronics has successfully manufactured a 16-layer stacked HBM3 memory based on hybrid bonding technology. The memory sample works normally. In the future, the 16-layer stacked hybrid bonding technology will be used for mass production of HBM4 memory. ▲Image source TheElec, same as below. Compared with the existing bonding process, hybrid bonding does not need to add bumps between DRAM memory layers, but directly connects the upper and lower layers copper to copper.

According to news from this website on May 6, Lexar launched the Ares Wings of War series DDR57600CL36 overclocking memory. The 16GBx2 set will be available for pre-sale at 0:00 on May 7 with a deposit of 50 yuan, and the price is 1,299 yuan. Lexar Wings of War memory uses Hynix A-die memory chips, supports Intel XMP3.0, and provides the following two overclocking presets: 7600MT/s: CL36-46-46-961.4V8000MT/s: CL38-48-49 -1001.45V In terms of heat dissipation, this memory set is equipped with a 1.8mm thick all-aluminum heat dissipation vest and is equipped with PMIC's exclusive thermal conductive silicone grease pad. The memory uses 8 high-brightness LED beads and supports 13 RGB lighting modes.

Some users encountered a memory error prompt when using Win10, called "The memory cannot be written". What is going on? Below, the editor will share with you the solution to the Windows 10 system prompt "The memory cannot be written" 1. Press win+r to open the run function on the computer, enter services and msc, and then click OK. 2. Find the Windows Management Instrumentation service in the services window, click "Stop", and then click OK. 3. Still press win+r to open the computer’s run function and enter

According to news from this site on June 7, GEIL launched its latest DDR5 solution at the 2024 Taipei International Computer Show, and provided SO-DIMM, CUDIMM, CSODIMM, CAMM2 and LPCAMM2 versions to choose from. ▲Picture source: Wccftech As shown in the picture, the CAMM2/LPCAMM2 memory exhibited by Jinbang adopts a very compact design, can provide a maximum capacity of 128GB, and a speed of up to 8533MT/s. Some of these products can even be stable on the AMDAM5 platform Overclocked to 9000MT/s without any auxiliary cooling. According to reports, Jinbang’s 2024 Polaris RGBDDR5 series memory can provide up to 8400

According to a TrendForce survey report, the AI wave has a significant impact on the DRAM memory and NAND flash memory markets. In this site’s news on May 7, TrendForce said in its latest research report today that the agency has increased the contract price increases for two types of storage products this quarter. Specifically, TrendForce originally estimated that the DRAM memory contract price in the second quarter of 2024 will increase by 3~8%, and now estimates it at 13~18%; in terms of NAND flash memory, the original estimate will increase by 13~18%, and the new estimate is 15%. ~20%, only eMMC/UFS has a lower increase of 10%. ▲Image source TrendForce TrendForce stated that the agency originally expected to continue to

Detailed explanation of the method of converting int type to string in PHP In PHP development, we often encounter the need to convert int type to string type. This conversion can be achieved in a variety of ways. This article will introduce several common methods in detail, with specific code examples to help readers better understand. 1. Use PHP’s built-in function strval(). PHP provides a built-in function strval() that can convert variables of different types into string types. When we need to convert int type to string type,
