【发布时间】: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