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

没有重复项数字的全排列

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

import java.util.*;


public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param num int整型一维数组 
     * @return int整型ArrayList<ArrayList<>>
     */
    public ArrayList<ArrayList<Integer>> permute (int[] num) {
        // write code here
        int length = num.length;
        ArrayList<ArrayList<Integer>> lists = new ArrayList<> ();
        if(length == 0) return lists;
        Stack<Integer> path = new Stack<>();
        boolean[] isUsed = new boolean[length];
        dfs(num, length, 0, path, isUsed, lists);
        return lists;
    }

    private static void dfs(int[] num, int len, int depth, Stack<Integer> path, boolean[] isUsed, ArrayList<ArrayList<Integer>> lists){
        if(depth == len){
            lists.add(new ArrayList<Integer>(path));
            return;
        }else{
            for(int i = 0; i < len; i++){
                if(isUsed[i])  continue;
                path.add(num[i]);
                isUsed[i] = true;
                dfs(num, len, depth+1, path, isUsed, lists);
                isUsed[i] = false;
                path.pop();
            }
        }
    }
}

全部评论

相关推荐

06-08 22:25
门头沟学院 Java
从零开始的转码生活:这hr不会打开手机不分青红皂白给所有人群发这句话,过一会再给所有人再发一遍,这肯定会有重复的,不管,再过一会再发一遍
点赞 评论 收藏
分享
06-10 21:15
门头沟学院 Java
宁阿:好多这种没🧠的公司,他们估计都不知道毕业的人不能给安排实习岗
实习吐槽大会
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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