javascript - 这种组合生成递归有什么问题?
问题描述
我有以下代码:
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
应该归咎于电话?
解决方案
仍然不能 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
,保持不变性。
推荐阅读
- angular - 无法从数据库中获取学生并将其显示在角度前端没有可见错误
- c# - DataGrid new DataContext 之后的事件
- vb.net - VB.NET 数据集“值已存在”处理
- amazon-web-services - AWS SQS 总是返回 1 条消息(PHP 开发工具包)
- ios - 如何在不使用 UIWebView 的 iOS 中打开 PDF?
- fortran - 调用的 Fortran 代码的每一行末尾的“后缀”语法是什么?
- python - Python Windows cmd 命令格式
- hibernate - 休眠针对多对一关系执行的多个查询
- java - 在休眠中替换父级的最佳方法
- opencv - 使用 OpenCV 提取文本和边界框