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);
        }
    }   
}
相关推荐
uesowys7 分钟前
Apache Spark算法开发指导-Factorization machines classifier
人工智能·算法
TracyCoder12326 分钟前
LeetCode Hot100(26/100)——24. 两两交换链表中的节点
leetcode·链表
季明洵34 分钟前
C语言实现单链表
c语言·开发语言·数据结构·算法·链表
shandianchengzi39 分钟前
【小白向】错位排列|图文解释公考常见题目错位排列的递推式Dn=(n-1)(Dn-2+Dn-1)推导方式
笔记·算法·公考·递推·排列·考公
I_LPL39 分钟前
day26 代码随想录算法训练营 回溯专题5
算法·回溯·hot100·求职面试·n皇后·解数独
Yeats_Liao40 分钟前
评估体系构建:基于自动化指标与人工打分的双重验证
运维·人工智能·深度学习·算法·机器学习·自动化
only-qi43 分钟前
leetcode19. 删除链表的倒数第N个节点
数据结构·链表
cpp_250144 分钟前
P9586 「MXOI Round 2」游戏
数据结构·c++·算法·题解·洛谷
浅念-1 小时前
C语言编译与链接全流程:从源码到可执行程序的幕后之旅
c语言·开发语言·数据结构·经验分享·笔记·学习·算法
爱吃生蚝的于勒1 小时前
【Linux】进程信号之捕捉(三)
linux·运维·服务器·c语言·数据结构·c++·学习