You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将树形分支结构的数组元素进行展开分配?

数组分配展开问题的递归解法

输入数组结构:

[
  ["a", "b"],
  [
    ["c", "d"],
    ["e", "f", "g"]
  ],
  [
    ["h", "i"],
    ["j"],
    ["k", "l"],
    ["m"],
    ["n", "o", "p"]
  ]
]

需要转换为目标结果:

["ach", "aci", "adj", "bek", "bel", "bfm", "bgn", "bgo", "bgp"]

分配规则

  • 第一阶段:
    • 将["c", "d"]分配到"a"上,得到["ac", "ad"]
    • 将["e", "f", "g"]分配到"b"上,得到["be", "bf", "bg"]
  • 第二阶段:
    • 将["h", "i"]分配到"ac"上,得到["ach", "aci"]
    • 将["j"]分配到"ad"上,得到["adj"]
    • 将["k", "l"]分配到"be"上,得到["bek", "bel"]
    • 将["m"]分配到"bf"上,得到["bfm"]
    • 将["n", "o", "p"]分配到"bg"上,得到["bgn", "bgo", "bgp"]

原有代码问题

你写的递归函数逻辑错误,它把当前层的每个元素和下一层的所有结果做了全组合,但实际规则是当前层的第n个元素,对应下一层的第n个子数组进行分配,并非全排列组合。

正确递归实现(自动适配嵌套结构)

function distribute(arr) {
  // 基准情况:如果当前是字符串,包装为数组返回
  if (typeof arr === 'string') {
    return [arr];
  }
  // 只剩最后一层时,返回每个元素的处理结果
  if (arr.length === 1) {
    return arr[0].map(item => distribute(item)).flat();
  }

  const currentLayer = arr[0];
  const nextLayerResults = distribute(arr.slice(1));
  const result = [];
  let currentIndex = 0;

  // 按顺序将当前层元素与对应下一层子数组拼接
  for (const item of currentLayer) {
    const subGroup = nextLayerResults[currentIndex];
    result.push(...subGroup.map(subItem => item + subItem));
    currentIndex++;
  }

  return result;
}

const inputArray = [
  ["a", "b"],
  [["c", "d"], ["e", "f", "g"]],
  [["h", "i"], ["j"], ["k", "l"], ["m"], ["n", "o", "p"]]
];

console.log(distribute(inputArray));
// 输出:["ach", "aci", "adj", "bek", "bel", "bfm", "bgn", "bgo", "bgp"]

代码说明

  1. 基准处理:遇到字符串时直接包装为数组,确保后续拼接逻辑统一;只剩最后一层时,递归处理每个子元素后扁平化结果。
  2. 层级匹配:遍历当前层元素时,按顺序对应下一层返回的子结果组,将当前元素与子组内的每个元素拼接,保证分配规则的正确性。
  3. 自动适配嵌套:无需提前调整输入结构,函数会自动识别多层嵌套的数组关系。

内容的提问来源于stack exchange,提问作者Vincent

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.08 21:45:00