算法通关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;
        }
    }
相关推荐
孤飞5 小时前
zero2Agent:面向大厂面试的 Agent 工程教程,从概念到生产的完整学习路线
算法
技术专家6 小时前
Stable Diffusion系列的详细讨论 / Detailed Discussion of the Stable Diffusion Series
人工智能·python·算法·推荐算法·1024程序员节
csdn_aspnet6 小时前
C# (QuickSort using Random Pivoting)使用随机枢轴的快速排序
数据结构·算法·c#·排序算法
鹿角片ljp6 小时前
最长回文子串(LeetCode 5)详解
算法·leetcode·职场和发展
广师大-Wzx8 小时前
一篇文章看懂MySQL数据库(下)
java·开发语言·数据结构·数据库·windows·python·mysql
paeamecium8 小时前
【PAT甲级真题】- Cars on Campus (30)
数据结构·c++·算法·pat考试·pat
chh5639 小时前
C++--模版初阶
c语言·开发语言·c++·学习·算法
RTC老炮9 小时前
带宽估计算法(gcc++)架构设计及优化
网络·算法·webrtc
dsyyyyy11019 小时前
计数孤岛(DFS和BFS解决)
算法·深度优先·宽度优先
会编程的土豆10 小时前
01背包与完全背包详解
开发语言·数据结构·c++·算法