46.全排列

给定一个不含重复数字的数组 nums ,返回其 所有可能的全排列 。你可以 按任意顺序 返回答案。

java 复制代码
class Solution {

    List<List<Integer>> res = new ArrayList<>();

    List<Integer> temp = new ArrayList<>();

    public List<List<Integer>> permute(int[] nums) {
        List<Integer> list = new ArrayList<>();
        backtrace(nums, list);
        return res;
    }

    // 用list记录添加过的下标。
    public void backtrace(int[] nums, List<Integer> list){
        if(list.size() == nums.length){
            res.add(new ArrayList(temp));
            return;
        }
        for(int i = 0; i < nums.length; i++){
            int num = nums[i];
            if(!list.contains(num)) {
                temp.add(num);
                list.add(num);
            } else continue;
            backtrace(nums, list);
            temp.remove(temp.size() - 1);
            list.remove(list.size() - 1);
        }
    }
    
}

其实可以直接不记录list,使用nums不重复的特性,在temp中判断是否加入过某个元素:

java 复制代码
class Solution {

    List<List<Integer>> res = new ArrayList<>();

    List<Integer> temp = new ArrayList<>();

    public List<List<Integer>> permute(int[] nums) {
        backtrace(nums);
        return res;
    }

    public void backtrace(int[] nums){
        if(temp.size() == nums.length){
            res.add(new ArrayList(temp));
            return;
        }
        for(int i = 0; i < nums.length; i++){
            // 因为nums不重复!
            int num = nums[i];
            if(!temp.contains(num)) {
                temp.add(num);
            } else continue;
            backtrace(nums);
            temp.remove(temp.size() - 1);
        }
    }   
}
相关推荐
weixin_458872611 小时前
东华复试OJ二刷复盘2
算法
Charlie_lll1 小时前
力扣解题-637. 二叉树的层平均值
算法·leetcode
爱淋雨的男人1 小时前
自动驾驶感知相关算法
人工智能·算法·自动驾驶
wen__xvn2 小时前
模拟题刷题3
java·数据结构·算法
滴滴答滴答答2 小时前
机考刷题之 6 LeetCode 169 多数元素
算法·leetcode·职场和发展
圣保罗的大教堂2 小时前
leetcode 1980. 找出不同的二进制字符串 中等
leetcode
Neteen2 小时前
【数据结构-思维导图】第二章:线性表
数据结构·c++·算法
礼拜天没时间.3 小时前
力扣热题100实战 | 第25期:K个一组翻转链表——从两两交换到K路翻转的进阶之路
java·算法·leetcode·链表·递归·链表反转·k个一组翻转链表
Swift社区3 小时前
LeetCode 400 第 N 位数字
算法·leetcode·职场和发展
再难也得平3 小时前
力扣239. 滑动窗口最大值(Java解法)
算法·leetcode·职场和发展