算法通关18关 | 回溯模板如何解决排列和单词搜索问题

1. 排列问题

题目

LeetCode46 给定一个没有重复数字的序列,返回其所有可能的全排列,

思路

排列问题的思路同样使用与字母大小写全排列LeetCode784。

元素在使用过一次的时候,在图中第二层的时候,还会再被使用,所以能用startIndex了,使用used[i]数组来标记已经选择的元素。过程如图示。

终止条件:收集元素的数组大小和nums数组的大小一样大的时候,就找到了一个全排列

代码

java 复制代码
    /**
     * 排列问题,同样适用于字母大小写全排列
     */
     List<List<Integer>> res = new ArrayList<>();

      LinkedList<Integer> path = new LinkedList<>();
    boolean[] used;

    public  List<List<Integer>> permure(int[] nums){
        if (nums.length == 0){
            return res;
        }
        used = new boolean[nums.length];
        psermuteHelper(nums);
        return res;
    }

    private  void psermuteHelper(int[] nums) {
        if (path.size() == nums.length){
            res.add(new ArrayList<>(path));
            return;
        }
        for (int i = 0; i < nums.length; i++) {
            //为true的时候代表再纵向被使用过,纵向第一条元素出来的时候,会转为false
            if (used[i]){
                continue;
            }
            used[i] = true;
            path.add(nums[i]);
            psermuteHelper(nums);
            path.removeLast();
            used[i] = false;
        }
    }
相关推荐
三毛的二哥6 小时前
BEV:典型BEV算法总结
人工智能·算法·计算机视觉·3d
南宫萧幕7 小时前
自控PID+MATLAB仿真+混动P0/P1/P2/P3/P4构型
算法·机器学习·matlab·simulink·控制·pid
故事和你918 小时前
洛谷-数据结构1-4-图的基本应用1
开发语言·数据结构·算法·深度优先·动态规划·图论
我叫黑大帅8 小时前
为什么map查找时间复杂度是O(1)?
后端·算法·面试
炽烈小老头9 小时前
【每天学习一点算法 2026/04/20】除自身以外数组的乘积
学习·算法
skilllite作者9 小时前
AI agent 的 Assistant Auto LLM Routing 规划的思考
网络·人工智能·算法·rust·openclaw·agentskills
破浪前行·吴10 小时前
数据结构概述
数据结构·学习
py有趣11 小时前
力扣热门100题之不同路径
算法·leetcode
_日拱一卒11 小时前
LeetCode:25K个一组翻转链表
算法·leetcode·链表
啊哦呃咦唔鱼11 小时前
LeetCodehot100-394 字符串解码
算法