const permute = function (nums) {
let results = [];
let go = (current) => {
if (current.length === nums.length) {
results.push(current);
}
nums.forEach(n => {
if (!current.includes(n)) {
go([...current, n]);
}
});
}
go([]);
return results;
};
// console.log(permute([1, 2, 3]));
上面是基础版本,下面为进阶
let names = ["iPhone X", "iPhone XS"]
let colors = ["黑色", "白色"]
let storages = ["64g", "256g"]
let combine = function (...chunks) {
let res = []
let helper = function (chunkIndex, prev) {
let chunk = chunks[chunkIndex]
let isLast = chunkIndex === chunks.length - 1
for (let val of chunk) {
let cur = prev.concat(val)
if (isLast) {
// 如果已经处理到数组的最后一项了 则把拼接的结果放入返回值中
res.push(cur)
} else {
helper(chunkIndex + 1, cur)
}
}
}
// 从属性数组下标为 0 开始处理
helper(0, [])
return res
}
// console.log(combine(names, colors, storages))
典型题目
var letterCombinations = function(digits) {
if(digits.length==0){
return []
}
let map={
2: ['a','b','c'],
3: ['d','e','f'],
4: ['g','h','i'],
5: ['j','k','l'],
6: ['m','n','o'],
7: ['p','q','r','s'],
8: ['t','u','v'],
9: ['w','x','y','z'],
}
let go=(path,cur,res)=>{
if(cur === digits.length){
res.push(path.join(''));
return;
}
let temp=map[digits[cur]];
temp.forEach((item,index)=>{
path.push(item);
go(path,cur+1,res);
path.pop();
})
return res;
}
return go([],0,[])
};