首页 > 解决方案 > 这种组合生成递归有什么问题?

问题描述

我有以下代码:

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应该归咎于电话?

标签: javascriptalgorithmcombinationspermutationpowerset

解决方案


仍然不能 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,保持不变性。


推荐阅读