腾讯常考十道算法真题:全排列(回溯算法解决)

2022-03-2709:43:40数据结构与算法Comments1,260 views字数 1013阅读模式

给定一个不含重复数字的数组 nums ,返回其 所有可能的全排列 。你可以 按任意顺序 返回答案。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/suanfa/23766.html

示例 1:文章源自菜鸟学院-https://www.cainiaoxueyuan.com/suanfa/23766.html

输入:nums = [1,2,3]
输出:[[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]

示例 2:文章源自菜鸟学院-https://www.cainiaoxueyuan.com/suanfa/23766.html

输入:nums = [0,1]
输出:[[0,1],[1,0]]

这道题可以用回溯算法解决,完整代码如下:文章源自菜鸟学院-https://www.cainiaoxueyuan.com/suanfa/23766.html

class Solution {
    //全排列,即所有路径集合
    List<List<Integer>> allPath = new LinkedList<>();

    public List<List<Integer>> permute(int[] nums) {
        //当前路径,入口路径,path是空的
        List<Integer> path =  new LinkedList<>();
        //递归函数入口,可做选择是nums数组
        backTrace(nums,path);
        return allPath;
    }

    public void backTrace(int[] nums,List<Integer> path){
        //已走路径path的数组长度等于nums的长度,表示走到叶子节点,所以加到全排列集合
        if(nums.length==path.size()){
           allPath.add(new LinkedList(path));
           return;
        }

        for(int i=0;i<nums.length;i++){
            //剪枝,排查已经走过的路径
            if(path.contains(nums[i])){
                continue;
            }
            //做选择,加到当前路径
            path.add(nums[i]);
            //递归,进入下一层的决策
            backTrace(nums,path);
            //取消选择
            path.remove(path.size() - 1);
        }
    }
}
文章源自菜鸟学院-https://www.cainiaoxueyuan.com/suanfa/23766.html
  • 本站内容整理自互联网,仅提供信息存储空间服务,以方便学习之用。如对文章、图片、字体等版权有疑问,请在下方留言,管理员看到后,将第一时间进行处理。
  • 转载请务必保留本文链接:https://www.cainiaoxueyuan.com/suanfa/23766.html

Comment

匿名网友 填写信息

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定