回溯算法在前端的应用 - 电商SKU全排列算法

2022/3/29 9:27:09

本文主要是介绍回溯算法在前端的应用 - 电商SKU全排列算法,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

/**
 输入:
    const systems = ["mac", "windows"]
    const prices = ["$5000", "$10000"]
    const storages = ["512g", "1T"]
 返回:
    [
        ["mac", "$5000", "512g"],
        ["mac", "$5000", "1T"],
        ["mac", "$10000", "512g"],
        ["mac", "$10000", "1T"],
        ["windows", "$5000", "512g"],
        ["windows", "$5000", "1T"],
        ["windows", "$10000", "512g"],
        ["windows", "$10000", "1T"]
    ]

 思路:
    cateIndex 控制树的纵向遍历
    traverse 控制树的横向遍历

    递归出口:
        总是在最后一个cate数组,即叶子节点时, 将状态的累积part添加至结果数组res
 */

const systems = ["mac", "windows"]
const prices = ["$5000", "$10000"]
const storages = ["512g", "1T"]
const genCombination = (...cateArrs) => {
    const res = []
    const totalCount = cateArrs.length
    const traverse = (part, cateIndex) => {
        cateArrs[cateIndex].forEach(v => {
            const cur = part.concat(v)
            cateIndex === totalCount - 1 ? res.push(cur) : traverse(cur, cateIndex + 1)
        })
    }
    traverse([], 0)
    return res
}

console.log(genCombination(systems, prices, storages))



这篇关于回溯算法在前端的应用 - 电商SKU全排列算法的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程