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);
        }
    }   
}
相关推荐
柏箱1 小时前
容器里有10升油,现在只有两个分别能装3升和7升油的瓶子,需要将10 升油等分成2 个5 升油。程序输出分油次数最少的详细操作过程。
算法·bfs
Hello eveybody3 小时前
C++介绍整数二分与实数二分
开发语言·数据结构·c++·算法
Mallow Flowers5 小时前
Python训练营-Day31-文件的拆分和使用
开发语言·人工智能·python·算法·机器学习
梦境虽美,却不长5 小时前
数据结构 学习 队列 2025年6月14日 11点22分
数据结构·学习·队列
GalaxyPokemon5 小时前
LeetCode - 704. 二分查找
数据结构·算法·leetcode
leo__5206 小时前
matlab实现非线性Granger因果检验
人工智能·算法·matlab
GG不是gg6 小时前
位运算详解之异或运算的奇妙操作
算法
FF-Studio8 小时前
万物皆数:构建数字信号处理的数学基石
算法·数学建模·fpga开发·自动化·音视频·信号处理·dsp开发
hy.z_7778 小时前
【数据结构】 优先级队列 —— 堆
数据结构
你的牧游哥8 小时前
前端面试题之将自定义数据结构转化成DOM元素
数据结构