[英]How to avoid my permutation algorithm of ERROR:heap out memory
Today I try to solve a problem on codewars ,it requires me give the permutations of a given string. 今天,我尝试解决有关代码战的问题,它要求我给出给定字符串的排列。
Firstly,I try to use a recursion function looks like: 首先,我尝试使用如下所示的递归函数:
function permutate(str) {
var result = [];
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++) {
var temp = preResult[j].slice(0, k) + str[0] + preResult[j].slice(k);
result.push(temp);
}
}
return result;
}
}
After I click the attemp button,the OJ tells me there is an error caused by heap out memory.Because my function called with a long string:"abcdefghijkl". 单击attemp按钮后,OJ会告诉我是由于堆满内存引起的错误。因为我的函数调用时带有长字符串:“ abcdefghijkl”。
Secondly,I rewrite my function by using loop.just like: 其次,我使用loop。重写我的函数,就像:
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;
}
It works when the given string is short.But still cause Error. 当给定的字符串很短时可以使用,但是仍然会导致错误。
So,I want to know why cause this error and if there is a permutation algorithm can run in Node(v6.11.0) without memory error? 那么,我想知道为什么会导致此错误,并且是否存在可以在Node(v6.11.0)中运行而没有内存错误的置换算法?
I searched a lot and tried many methods,but nothing works.So I ask my first question on stackoverflow,hoping you can give me some help.Thanks! 我搜索了很多东西,尝试了很多方法,但是没有用。所以我问了我关于stackoverflow的第一个问题,希望可以给我一些帮助。谢谢!
尝试使用模块https://github.com/miguelmota/permutations ,甚至尝试使用模块中的代码
除了可以尝试的先前答案外,您还可以尝试增加进程的最大内存限制大小,例如,使用node --max-old-space-size=8192
(以字节为单位),则节点进程将以扩展的8GB运行内存限制。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.