Skip to content

记一个路径遍历算法(JS)

js
/**
 * 输入
 * ["A", "B"],
   ["C", "D"],
   ["E", "F"],
   输出
  ["A", "C", "E"],
  ["A", "C", "F"],
  ["A", "D", "E"],
  ["A", "D", "F"],
  ["B", "C", "E"],
  ["B", "C", "F"],
  ["B", "D", "E"],
  ["B", "D", "F"],
 */
function transform(input) {
  const cr = [];
  const result = [];
  function rec(input, level, maxLevel) {
    if (level >= maxLevel) {
      result.push([...cr]);
      return;
    }
    const currentRow = input[level];
    currentRow.forEach((item) => {
      cr[level] = item;
      rec(input, level + 1, maxLevel);
    });
  }

  rec(input, 0, input.length);

  return result;
}

最后编辑时间:

Version 4.2 (core-1.3.4)