侧边栏壁纸
博主头像
lmg博主等级

  • 累计撰写 55 篇文章
  • 累计创建 6 个标签
  • 累计收到 2 条评论
标签搜索

全排列

lmg
lmg
2020-05-01 / 0 评论 / 0 点赞 / 300 阅读 / 1,025 字
温馨提示:
本文最后更新于 2022-04-16,若内容或图片失效,请留言反馈。部分素材来自网络,若不小心影响到您的利益,请联系我们删除。

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

示例:

输入: [1,2,3]
输出:
[ [1,2,3], [1,3,2], [2,1,3], [2,3,1], [3,1,2], [3,2,1]]
链接:https://leetcode-cn.com/problems/permutations

回溯法

class Solution {
    public  List<List<Integer>> permute(int[] nums){
        int len = nums.length;
        List<List<Integer>> res = new ArrayList<>();
        if(len==0){
            return res;
        }
        Deque<Integer> path = new ArrayDeque<>();
        boolean[] used = new boolean[len];
        dfs(nums,len,0,path,used,res);
        return res;


    }

    private  void dfs(int[] nums, int len, int depth, Deque<Integer> path, boolean[] used, List<List<Integer>> res) {
        if(depth == len)//递归终止条件
        {
            res.add(new ArrayList<>(path));
            return;//不执行下面的逻辑
        }
        for(int i=0; i<len; i++){
            if(used[i])
                continue;
            path.addLast(nums[i]);
            used[i] = true;
            dfs(nums, len, depth+1, path, used, res);//dfs一定要写在for循环里面。。。。
            //回溯。。。。前面操作干了什么,就要反操作
            path.removeLast();
            used[i] = false;
        }
        /*这样写是错的。他只会返回一个结果。。。
        for(int i=0; i<len; i++){
            if(used[i])
                continue;
            path.addLast(nums[i]);
            used[i] = true;
            break;
        }
        dfs(nums, len, depth+1, path, used, res);//dfs一定要写在for循环里面。。。。
        //回溯。。。。
        path.removeLast();
        used[i] = false;
        */
        
    }
}
0

评论区