编码:
function recursiveParse(letters, index) {
var i,
index = index || 0;
stringOfLetters = '';
while(index < letters.length) {
stringOfLetters += letters[index] + recursiveParse(letters, ++index);
}
return stringOfLetters;
}
function calcPermutations(letters, index, permutations) {
var head,
index = index || 0,
i,
swapLetters,
permutation,
permutations = permutations || {};
swapLetters = function(letters, index1, index2) {
var tmp = letters[index2];
letters[index2] = letters[index1];
letters[index1] = tmp;
return letters;
}
if(index < letters.length) {
head = letters.splice(index, 1).join('');
for(i = 0; i < letters.length; i++) {
permutation = head + swapLetters(letters.slice(0), index, i).join('');
permutations[permutation] = true;
}
letters.splice(index, 0, head);
calcPermutations(letters, ++index, permutations);
}
return permutations;
}
function testPermutations() {
var expectedPermutations = ['atr', 'rat', 'rta', 'tar', 'tra', 'art'],
actualPermutations = calcPermutations(['a', 'r', 't']);
for(var i = 0; i < expectedPermutations.length - 1; i++) {
if(actualPermutations[expectedPermutations[i]] !== true) {
console.log("You're missing " + expectedPermutations[i]);
} else {
console.log("You've got " + expectedPermutations[i]);
}
}
return actualPermutations;
}
testPermutations();
当我运行testPermutations
并传入一个 3 个字母的单词时,它工作正常。但是,当我尝试四个时,会出现一堆排列丢失。我的逻辑有什么缺陷?