我理解一下题目:
二维数组 arr 每一行长度相等,求每一列对应字符的全排列
全排列用递归:
const matrix = [
['a', 'b', 'c'],
['1', '2', '3']
]
// 输入新字符和已有排列, 返回新排列
const fn = (resultArr, matrix, index = 0) => {
if (index >= matrix[0].length) return resultArr
const newResult = []
resultArr.forEach(arr => {
matrix.forEach(row => {
newResult.push([...arr, row[index]])
})
})
return fn(newResult, matrix, index + 1)
}
console.log(fn([''], matrix))
输出:
[
[ 'a', 'b', 'c' ],
[ 'a', 'b', '3' ],
[ 'a', '2', 'c' ],
[ 'a', '2', '3' ],
[ '1', 'b', 'c' ],
[ '1', 'b', '3' ],
[ '1', '2', 'c' ],
[ '1', '2', '3' ]
]
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…