You need to enable JavaScript to run this app. JavaScript矩阵数组组合算法实现 兼顾时间复杂度的最优方案咨询
优惠活动
大模型
产品
解决方案
定价
更多

JavaScript矩阵数组组合算法实现 兼顾时间复杂度的最优方案咨询

最优实现方案

实现思路:

  • 第一步:按对象键值对输入数组做分组,自动归集0/1/2对应的取值列表,不需要手动判断每个键
  • 第二步:对分组后的数组计算笛卡尔积,再按规则拼接字符串,时间复杂度和你原有方案一致,都是O(n)(n为最终组合数,是该组合逻辑场景下的理论最优时间复杂度,不可能比输出的组合数更少)
function getCombinations(input) {
  // 按key自动分组
  const groups = input.reduce((acc, item) => {
    const [key, value] = Object.entries(item)[0]
    const numKey = Number(key)
    if (!acc[numKey]) acc[numKey] = []
    acc[numKey].push(value)
    return acc
  }, [])

  // 通用笛卡尔积计算
  const cartesian = (arrays) => arrays.reduce((a, b) => a.flatMap(x => b.map(y => [...x, y])), [[]])

  const combinations = cartesian(groups)

  // 按规则拼接结果
  return combinations.map(item => {
    if (item.length === 1) return `${item[0]}.`
    return item.join('.')
  })
}

// 测试验证
const input5 = [ {0: "small"},{0: "large"}, {1: "red"},{1: "orange"},{1: "blue"},{2: "cake"},{2: "ice"}]
console.log(getCombinations(input5))

方案优势

  • 不需要手动写多层if嵌套和多个forEach循环,代码更简洁易维护
  • 后续如果key最大值超过3,不需要大幅修改逻辑,扩展性更强
  • 没有额外性能损耗,效率和你原有的手动实现完全一致

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.10 15:21:02