我被要求计算“点字机”的空间复杂度
我创建的函数。
该函数通过替换字母返回所有可能的字符串组合。
并具有一个“ memoization”对象来帮助提高计算性能。
所以问题是:如何计算此函数的空间复杂度?
代码:
const arrangeLetters = (function(){
let dat = {
memoization: {},
};
const arrange = ( word ) => {
if ( word.length < 2 ){
dat.memoization[word] = [word];
return [word]
}
var curLetter;
var restOfWord;
var newEntry='';
var allAnswers = [];
var index = 0;
var anagrams = [];
var i, j;
for ( i = 0; i < word.length; i++ ){
curLetter = word[i];
restOfWord = word.substr(0, i) + word.substr(i + 1, word.length - 1);
var shortwordArray = dat.memoization[restOfWord] || arrange(restOfWord);
for ( j = 0; j < shortwordArray.length; j++) {
newEntry = curLetter + shortwordArray[j];
anagrams[index++] = newEntry;
dat.memoization[curLetter + restOfWord] = anagrams;
allAnswers.push(newEntry);
}
}
return allAnswers;
};
return arrange;
})();
console.log(arrangeLetters('abefghi'));