这种组合生成的递归有什么问题?

时间:2018-08-07 09:18:52

标签: javascript algorithm combinations permutation powerset

我有以下代码:

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的电话应该受到指责?

2 个答案:

答案 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);