我有以下代码:
const findMult_3 = (num) => {
const powerset = (set) => {
const combinations = []
const combine = (prefix, chars) => {
for (let i = 0; i < chars.length; i++) {
combinations.push(prefix + chars[i])
combine(prefix + chars[i], chars.slice(i + 1))
}
}
combine('', set)
return combinations
}
const allCombinations = powerset(num.toString().split(''))
console.log(allCombinations)
}
findMult_3(362)
我希望它能起作用,但是,在输入362
的情况下,功能控制台将记录:
[ '3', '36', '362', '32', '6', '62', '2' ]
它缺少诸如63, 23, 26
等的变体。似乎slice
的电话应该受到指责?
答案 0 :(得分:1)
仍不能100%确认slice
调用是什么问题,但我通过回避该问题并避免对数组进行变异来解决此问题:
const findMult_3 = (num) => {
const powerset = (set) => {
const combinations = []
const combine = (prefix, chars) => {
for (let i = 0; i < chars.length; i++) {
combinations.push(prefix + chars[i])
combine(prefix + chars[i], chars.filter((x, ind) => ind !== i))
}
}
combine('', set)
return combinations
}
const allCombinations = powerset(num.toString().split(''))
console.log(allCombinations)
}
findMult_3(362)
请注意使用filter
代替splice
,以保持不变性。
答案 1 :(得分:-1)
我发现了问题,将数组复制到了c,然后删除了要与之合并的元素:
const findMult_3 = (num) => {
const powerset = (set) => {
const combinations = []
const combine = (prefix, chars) => {
console.log(chars);
for (let i = 0; i < chars.length; i++) {
combinations.push(prefix + chars[i])
var c = chars.slice();
c.splice(i,1);
combine(prefix + chars[i], c);
}
}
combine('', set)
return combinations
}
const allCombinations = powerset(num.toString().split(''));
console.log(allCombinations);