首页 > 其他分享 >【DFS】LeetCode 46. 全排列

【DFS】LeetCode 46. 全排列

时间:2023-03-06 13:35:57浏览次数:47  
标签:used nums 46 DFS 排列 dfs new path LeetCode

题目链接

46. 全排列

思路

本题是求排列问题.与组合问题不同的是,在排列问题中,不同的数字顺序被视为不同的排列,比如 [1,2][2,1] 是两种不同的排列。

搜索树如下图所示,引用自代码随想录

image

在组合问题的 dfs 算法上进行一点小修改即可,参考【DFS】LeetCode 78. 子集的代码,将 for 的初始化由 i = index 改为 i = 0

代码

class Solution {
    private List<List<Integer>> result = new ArrayList<>();
    private Deque<Integer> path = new ArrayDeque<>();
    private boolean[] used;

    public List<List<Integer>> permute(int[] nums) {
        used = new boolean[nums.length];

        dfs(nums);

        return result;
    }

    void dfs(int[] nums){
        if(path.size() == nums.length){
            result.add(new ArrayList<>(path));
            return;
        }

        for(int i = 0; i < nums.length; i++){
            if(!used[i]){
                path.addLast(nums[i]);
                used[i] = true;
                dfs(nums);
                used[i] = false;
                path.removeLast();
            }
        }
    }
}

标签:used,nums,46,DFS,排列,dfs,new,path,LeetCode
From: https://www.cnblogs.com/shixuanliu/p/17183502.html

相关文章

  • LeetCode -- 只出现一次的数字
    problem11.题目描述2.思路3.代码problem21.题目描述2.思路3.代码problem31.题目描述2.思路3.代码problem41.题目描述......
  • 【DFS】LeetCode 90. 子集 II
    题目链接90.子集II思路去重方法与【DFS】LeetCode40.组合总和II思路相似代码classSolution{privateList<List<Integer>>result=newArrayList<>();......
  • DFS 序求 LCA
    很冷门的科技,但是有着显著的使用效果(减少建立虚树的常数)。本文学习自:Alex_Wei的博客首先遍历一遍整棵树,可以得到整棵树的DFS序和每个点的时间戳(记为\(dfn\))。考虑......
  • 【DFS】LeetCode 78. 子集
    题目链接78.子集思路求子集问题和77.组合(opensnewwindow)和131.分割回文串(opensnewwindow)又不一样了。如果把子集问题、组合问题、分割问题都抽象为一......
  • 【DFS】LeetCode 216. 组合总和 III
    题目链接216.组合总和III思路与【DFS】LeetCode40.组合总和II思路一致,只不过candidates数组在题目中明确说明了只有1到9。代码classSolution{private......
  • #yyds干货盘点# LeetCode面试题:组合总和
    1.简述:给你一个无重复元素的整数数组 candidates和一个目标整数 target ,找出 candidates 中可以使数字和为目标数 target的所有 不同组合,并以列表形式返回。你......
  • #yyds干货盘点# LeetCode程序员面试金典:交换和
    题目:给定两个整数数组,请交换一对数值(每个数组中取一个数值),使得两个数组所有元素的和相等。返回一个数组,第一个元素是第一个数组中要交换的元素,第二个元素是第二个数组中要交......
  • LeetCode 周赛 335,纯纯手速场!
    本文已收录到AndroidFamily,技术和职场问题,请关注公众号[彭旭锐]提问。大家好,我是小彭。昨晚是LeetCode第335场周赛,你参加了吗?这场周赛整体难度不高,有两道模板题......
  • LeetCode 96. 不同的二叉搜索树(/)
    原题解题目约束题解方法一classSolution{public:intnumTrees(intn){vector<int>G(n+1,0);G[0]=1;G[1]=1;......
  • 【LeetCode二叉树#20】二叉搜索树转换为累加树,巩固二叉树的遍历(特殊的中序遍历)
    将二叉搜索树转换为累加树力扣题目链接(opensnewwindow)给出二叉搜索树的根节点,该树的节点值各不相同,请你将其转换为累加树(GreaterSumTree),使每个节点node的新值......