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

有重复项数字的全排列

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

import java.util.*;

public class Solution {
    public ArrayList<ArrayList<Integer>> permuteUnique(int[] num) {
 ArrayList<ArrayList<Integer>> ret = new ArrayList<ArrayList<Integer>>();
        int len = num.length;
        dfs(num, ret, 0);
        Collections.sort(ret, new Comparator<ArrayList<Integer>>() {
            @Override
            public int compare(ArrayList<Integer> o1, ArrayList<Integer> o2) {
                StringBuilder oo1 = new StringBuilder();
                StringBuilder oo2 = new StringBuilder();
                o1.stream().forEach(x -> oo1.append(x));
                o2.stream().forEach(x -> oo2.append(x));
                return o1.toString().compareTo(o2.toString());
            }
        });
        return ret;
    }
public void dfs(int[] nums, ArrayList<ArrayList<Integer>> ret, int k) {
        if (k == nums.length) {
            ArrayList<Integer> list = new ArrayList<>();
            for (int i = 0; i < nums.length; i++) {
                list.add(nums[i]);
            }

            ret.add(list);
            return;
        }
        List<Integer> tempList=new ArrayList<>();
        for (int i = k; i < nums.length; i++) {
            if(i!=k&&nums[i]==nums[k]||tempList.contains(nums[i])){
                continue;
            }
            swap(nums, k, i);
          
            dfs(nums, ret, k + 1);
            swap(nums, k, i);
            tempList.add(nums[i]);
        }
    }
       public void swap(int[] nums, int i, int j) {
        int temp = nums[i];
        nums[i] = nums[j];
        nums[j] = temp;
    }

    
}

全部评论

相关推荐

不愿透露姓名的神秘牛友
11-26 15:46
已编辑
字节国际 电商后端 24k-35k
点赞 评论 收藏
分享
我见java多妩媚:大外包
点赞 评论 收藏
分享
评论
点赞
收藏
分享
牛客网
牛客企业服务