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

有重复项数字的全排列

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

代码简单,容易懂

import java.util.*;

public class Solution {

    ArrayList<ArrayList<Integer>> ans;
    boolean[] st;

    public ArrayList<ArrayList<Integer>> permuteUnique(int[] num) {
        ans = new ArrayList<>();
        Arrays.sort(num);
        st = new boolean[num.length];
        dfs(num, new ArrayList<>());
        return ans;
    }

    private void dfs(int[] num, ArrayList<Integer> temp) {
        if (temp.size() == num.length) {
            ans.add(new ArrayList<>(temp));
            return;
        }
        HashSet<Integer> set = new HashSet<>();
        for (int i = 0; i < num.length; i ++ ) {
            if (set.contains(num[i])) continue;
            if (st[i]) continue;
            temp.add(num[i]);
            set.add(num[i]);
            st[i] = true;
            dfs(num, temp);
            st[i] = false;
            temp.remove(temp.size() - 1);
        }
    }
}

全部评论

相关推荐

积极的小学生不要香菜:你才沟通多少,没500不要说难
点赞 评论 收藏
分享
MinJerous:虽然我一直说 计算机不怎么卡学历 但是至少得一本
点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
07-08 14:10
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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