回溯法 | 没有重复元素的全排列

class Solution {
    List<List<Integer>> ress = new ArrayList<>();
    public List<List<Integer>> permute(int[] nums) {
        Arrays.sort(nums);
        int[] visited = new int[nums.length];
        dfs(nums,new ArrayList<>(),visited);
        return ress;
    }
    public void dfs(int[] nums, List<Integer> res, int[] visited){
        if(res.size()==nums.length){
            ress.add(new ArrayList<>(res));
            return;
        }
        for(int i=0;i<nums.length;i++){
            if(visited[i]==1) continue;
            if(i>0 && nums[i]==nums[i-1])continue;
            visited[i] = 1;
            res.add(nums[i]);
            dfs(nums,res,visited);
            visited[i] = 0;
            res.remove(res.size()-1);
        }
    }
}


全部评论
排序是面试中的常见提醒啊
点赞 回复 分享
发布于 2022-08-13 02:25

相关推荐

05-22 12:44
已编辑
门头沟学院 golang
点赞 评论 收藏
分享
06-02 15:17
门头沟学院 Java
心爱的idea:怎么会呢 应该是打招呼有问题 问就说实习6个月全国可飞随时到岗
点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
昨天 13:54
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务