题目
思路
试探-回溯法
解题过程
对于每个位置,试探放入一个可选的值,然后再递归地试探下一个位置,试探结束后回溯到上一层的状态。当某次试探中发现缓存已达到指定长度,则推入结果数组(注意此处不需要清除缓存,因为还需要供下一轮试探使用)。注意推入缓存的时候要复制而非浅拷贝,因为数组内容总是在变化的。
复杂度
- 时间复杂度: O(n∗n!)
- 空间复杂度: O(n)
代码
function permute(nums: number[]): number[][] {
const result: number[][] = [];
const allSet = new Set(nums);
// 获取剩余可选的数字
const getCandidates = (res: number[]): number[] => {
const visitedSet = new Set(res);
const restSet = new Set<number>();
for (const n of allSet.keys()) {
if (!visitedSet.has(n)) {
restSet.add(n);
}
}
return Array.from(restSet);
}
// 回溯
const backtrack = (res: number[]) => {
const index = res.length;
if (index === nums.length) {
// 已完成最后一个位置的填写
result.push([...res]);
return;
}
const candidates = getCandidates(res);
for (const c of candidates) {
res.push(c);
backtrack(res);
res.pop();
}
}
backtrack([]);
return result;
};
401

被折叠的 条评论
为什么被折叠?



