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

有重复项数字的全排列

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

import java.util.*;
public class Solution {
    public void recursion(ArrayList<ArrayList<Integer>> res, int[] num, ArrayList<Integer> temp, Boolean[] vis){
        //临时数组满了加入输出
        if(temp.size() == num.length){ 
            res.add(new ArrayList<Integer>(temp));
            return;
        }
	  	//ArrayList<Integer> chosed = new ArrayList<>();
        //遍历所有元素选取一个加入
        for(int i = 0; i < num.length; i++){ 
		  	//if(!used[i] && (chosed.isEmpty() || !chosed.contains(num[i])))
            //如果该元素已经被加入了则不需要再加入了
            if(vis[i]) 
                continue;
            if(i > 0 && num[i - 1] == num[i] && !vis[i - 1]) 
                //当前的元素num[i]与同一层的前一个元素num[i-1]相同且num[i-1]已经用过了
                continue;  
            //标记为使用过
            vis[i] =  true;  
            //加入数组
            temp.add(num[i]); 
            recursion(res, num, temp, vis);
            //回溯
            vis[i] =  false; 
            temp.remove(temp.size() - 1);
        }
    }
    public ArrayList<ArrayList<Integer>> permuteUnique(int[] num) {
        //先按字典序排序
        Arrays.sort(num);  
        Boolean[] vis = new Boolean[num.length];
        Arrays.fill(vis, false);
        ArrayList<ArrayList<Integer> > res = new ArrayList<ArrayList<Integer>>();
        ArrayList<Integer> temp = new ArrayList<Integer>();
        recursion(res, num, temp, vis);
        return res;
    }
}

本人的做法是在每一层新建一个集合,用来保存每一层遍历过的数字,最后排序,奈何“结果按照字典序排序”这一条过不了。

全部评论

相关推荐

深夜书店vv:腾讯是这样的,去年很多走廊都加桌子当工区
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务