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

有重复项数字的全排列

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);
        }
    }
}

全部评论

相关推荐

码农索隆:以下是我以我微薄的认知提供的建议: 1.考个教师资格证,去当体育考试。 2.去健身房当健身教练(因为在我印象里面体育生身材都不错)。
点赞 评论 收藏
分享
2025-12-19 21:53
门头沟学院 Java
想做OpenGL:不要一来就把自己定位这么低吧,把大厂当成目标,不断去学技术做项目,最后你至少能学到能找到中小厂的技术水平,你一上来就找这种两千块还要前后端都会的,其实对你用处不会很大,真去了也是打杂
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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