题解 | #没有重复项数字的所有排列#

没有重复项数字的所有排列

http://www.nowcoder.com/practice/4bcf3081067a4d028f95acee3ddcd2b1

    public ArrayList<ArrayList<Integer>> permute(int[] num) {
        // 存一种排列
        LinkedList<Integer> list = new LinkedList<>();
        // 递归进行
        backTrack(num,list);
        return res2;
    }
 
    public void backTrack(int[] num, LinkedList<Integer> list){
        // 当list中的长度等于数组的长度,则证明此时已经找到一种排列了
        if(list.size() == num.length){
            // add进返回结果集中
            res2.add(new ArrayList<>(list));
            return;
        }
        // 遍历num数组
        for(int i = 0; i < num.length; i++){
            // 若当前位置中的数已经添加过了则跳过
            if(list.contains(num[i]))
                continue;
            // 选择该数
            list.add(num[i]);
            // 继续寻找
            backTrack(num,list);
            // 撤销最后一个
            list.removeLast();
        }
    }
全部评论
他这个少了个语句,就是名为 res2 的二维链表,放到函数外面,就可以了。
2 回复 分享
发布于 2022-08-19 21:31 陕西

相关推荐

04-09 09:47
门头沟学院 Java
Arbelite_:2-3k,这工资还不如去摇奶茶
点赞 评论 收藏
分享
04-25 10:45
东南大学 Java
点赞 评论 收藏
分享
评论
21
2
分享

创作者周榜

更多
牛客网
牛客企业服务