// 回溯最主要还是那个index
const sku = () => {
let iphone = ["11", "12"];
let color = ["red", "blue"];
let memory = ["64", "256"];
const combine = (...chunks: string[][]) => {
console.log(chunks);
let res: string[][] = [];
const helper = (chunkIndex: number, prev: string[]) => {
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 {
console.log(cur);
helper(chunkIndex + 1, cur);
}
}
};
helper(0, []);
return res;
};
console.log(combine(iphone, color, memory));
};
//暴力回溯
const combine = (n: number, k: number): number[][] => {
const ans: number[][] = [];
let temp: number[] = [];
const dfs = (n: number, k: number, cur: number) => {
if (temp.length === k) {
ans.push([...temp]);
}
for (let i = cur; i <= n; i++) {
temp.push(i);
dfs(n, k, i + 1);
temp.pop();
}
};
dfs(n, k, 1);
console.log(ans);
return ans;
};
标签:const,cur,记录,number,例子,let,回溯,chunks,chunkIndex
From: https://www.cnblogs.com/gzeal/p/16709628.html