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

有重复项数字的全排列

https://www.nowcoder.com/practice/a43a2b986ef34843ac4fdd9159b69863

import java.util.*;

public class Solution {
    public ArrayList<ArrayList<Integer>> permuteUnique(int[] num) {
        ArrayList<ArrayList<Integer>> ans = new ArrayList<>();
        Arrays.sort(num);
        boolean[] isVisited = new boolean[num.length];
        int length = num.length;
        DFS(num, isVisited, ans, new ArrayList<>(), length);
        return ans;
    }
    public void DFS(int[] num, boolean[] isVisited,
                    ArrayList<ArrayList<Integer>> ans, ArrayList<Integer> temp, int length) {
        if (length == 0 && !ans.contains(temp)) {
            ans.add(new ArrayList<>(temp));
            return;
        } else {
            for (int i = 0; i < num.length; i++) {
                if (!isVisited[i]) {
                    isVisited[i] = true;
                    temp.add(num[i]);
                    DFS(num, isVisited, ans, temp, length - 1);
                    temp.remove(temp.size() - 1);
                    isVisited[i] = false;
                }
            }
        }
    }
}

全部评论

相关推荐

想按时下班的大菠萝在...:隔壁学校的,加油多投, 实在不好找可以下个学期开学找,把算法八股准备好,项目有空再换换
投了多少份简历才上岸
点赞 评论 收藏
分享
评论
2
收藏
分享

创作者周榜

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