【LeetCode】全排列

题目

Problem: 46. 全排列

思路

试探-回溯法

解题过程

对于每个位置,试探放入一个可选的值,然后再递归地试探下一个位置,试探结束后回溯到上一层的状态。当某次试探中发现缓存已达到指定长度,则推入结果数组(注意此处不需要清除缓存,因为还需要供下一轮试探使用)。注意推入缓存的时候要复制而非浅拷贝,因为数组内容总是在变化的。

复杂度

  • 时间复杂度: 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;
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值