Permutations II

Given a collection of numbers that might contain duplicates, return all possible unique permutations.

For example,
[1,1,2] have the following unique permutations:
[1,1,2][1,2,1], and [2,1,1].

参考:

水中的鱼: [LeetCode] Permutations II 解题报告

[解题思路]
跟 Permutations的解法一样,就是要考虑“去重”。先对数组进行排序,这样在DFS的时候,可以先判断前面的一个数是否和自己相等,相等的时候则前面的数必须使用了,自己才能使用,这样就不会产生重复的排列了。

public class Solution {
    
    public ArrayList<ArrayList<Integer>> permuteUnique(int[] num){
       ArrayList<ArrayList<Integer>> result = new  ArrayList<ArrayList<Integer>>();
        ArrayList<Integer> output = new ArrayList<Integer>();
        boolean[] visited = new boolean[num.length];
        Arrays.sort(num);
       getPermutation(0, num, output, result, visited);
       return result;
    }
    
    private void getPermutation(int depth, int[] num, ArrayList<Integer> output, ArrayList<ArrayList<Integer>> result, boolean[] visited){
        if(depth == num.length){
             ArrayList<Integer> tmp = new ArrayList<Integer>();
             tmp.addAll(output);
             result.add(tmp);
        }
        
        for(int i= 0 ; i< num.length; i++){
            if(visited[i] == false) {
                if(i>0 && num[i-1] == num[i] && visited[i-1]== false){
                    continue;
                }
                visited[i] = true;
                output.add(num[i]);
                getPermutation(depth+1, num, output, result, visited);
                output.remove(output.size() -1);
                 visited[i] = false;
         }
        }
        
    }
}
原文地址:https://www.cnblogs.com/RazerLu/p/3540011.html