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;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34