排列组合

103 阅读1分钟
let matrix = [
	['a','b','c'],
    [1,2,3],
    ['#','$'],
];

function combine(matrix) {
  // recurse
  function dfs(matrix, index) {
    console.log(index);
    if (index >= matrix.length) {
      return [];
    }

    if (index + 1 === matrix.length) {
      return matrix[index];
    }

    let ans = [];
    let row = matrix[index];
    let rest = dfs(matrix, index+1);
    for (let item of row) {
      for (let item2 of rest) {
        ans.push(item + '/' + item2);
      }
    }
    return ans;
  }

  return dfs(matrix, 0);
};


combine(matrix);
// ["a/1/#", "a/1/$", "a/2/#", "a/2/$", "a/3/#", "a/3/$", "b/1/#", "b/1/$", "b/2/#", "b/2/$", "b/3/#", "b/3/$", "c/1/#", "c/1/$", "c/2/#", "c/2/$", "c/3/#", "c/3/$"]