【问题标题】:How to push different combos of elements into a new array?如何将不同的元素组合推入新数组?
【发布时间】:2021-10-30 11:23:59
【问题描述】:

我要回答的问题是:任意长度的组合

修改此函数,使其将 arr 元素的所有组合作为数组数组返回。使用递归!

这是我目前所拥有的:

function getAllCombos(arr, newArr = []) {
  if (arr[0] === undefined) return newArr
  newArr.push(arr)
  return getAllCombos(arr.slice(1), newArr)
}

console.log(getAllCombos(['a', 'b']));
console.log(getAllCombos(['a', 'b', 'c']))

它给了我这个结果:

[['a', 'b'], ['b']]
[['a', 'b', 'c'], ['b', 'c'], ['c']]

我希望得到这个结果:

[['a','b'], ['a'], ['b'], []]
 [['a', 'b', 'c'],['a', 'b'], ['a', 'c'], ['a'], ['b', 'c'], ['b'], ['c'], [],]

如何遍历数组以获得不同的组合?同时也不重复已经推送的数组? 以下是测试用例:

console.log(getAllCombos(['a', 'b'])); 
console.log(getAllCombos(['a', 'b', 'c']))

【问题讨论】:

  • 考虑从空数组开始构建,而不是从完整数组开始切片。

标签: javascript arrays recursion


【解决方案1】:

简答


const getAllCombosShort= array => array.reduce((acc, curr) => acc.flatMap(e => [e, [...e, curr]]), [[]])
console.log(getAllCombosShort(['a','b','c']));

详细解答


如何构造递归

递归意味着通过三个步骤构建您的解决方案:

  • 基本情况:空数组的所有组合只是一个内部有一个空数组的数组。

  • 归纳假设 (I.H.):假设已知如何获得任何长度为 n-1 的数组的所有组合。

  • 一般情况 (G.C.):证明您可以使用上一步求解任何长度为 n 的数组。

如何构造递归算法

通过递归得到解S的关键是找出如何从I.H.中扩展真理。去 G.C.

假设您向您最好的朋友之一提供了一些任意输入,作为回报,他为您提供了问题的解决方案S'。然而,由于他不想在银盘上将解决方案 S 提供给您,因此他接受了比原始输入少一个单位的所有工作部分。

有了他的解决方案S',你不仅可以用完整的输入解决问题,还可以自然地构建算法。

例如,['a','b', 'c']

  • 给他['b', 'c']并获取:
[ ['b','c'], ['b'], ['c'], [] ]
  • 对于它的每个元素,创建一个包含自身的新元素加上 'a' 并将其推送到 他的解决方案数组,即:
[     ['b','c'],     ['b'],     ['c'],   []  ,
  ['a','b','c'], ['a','b'], ['a','c'], ['a'] ]

伪代码

algorithm allCombos
  input: array of length n
  output: array of all combinations
   
if array is empty
       return an array with empty inside
head := head(array) -- head
tail := tail(array)
friend := allCombos(tail) -- your friend knows how to solve for one smaller
for each element of friends do
    new_elem := [...element, head]
    friend.push(new_elem)
return friend    

Javascript通讯员:

function getAllCombos(array) {
  if (array && array.length === 0) return [[]]
  let head = array[0]
  let tail = array.slice(1)
  friend = getAllCombos(tail)
  friend.forEach(elem => friend.push([head, ...elem]))
  return friend
}

console.log(getAllCombos(['a','b']))
console.log(getAllCombos(['a', 'b', 'c']))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-09-25
    • 2021-12-25
    • 2019-12-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-25
    • 2022-08-17
    相关资源
    最近更新 更多