Permutations II

来源:互联网 发布:软件实施工程师待遇 编辑:程序博客网 时间:2024/05/16 00:28

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].

Analysis: DFS. In order to avoid to generate duplicate permutations, we need a cache to store the numbers we have already used for the current position. Intuitively, if we use two same numbers in one position, all of the permutations generated by them will be exactly the same. Except for this "cache", everything is just the same as in Permutation I. 

public class Solution {    public void permuteUnique(int[] num, ArrayList<ArrayList<Integer>> res, ArrayList<Integer> tem) {        if(num.length == 0) {            ArrayList<Integer> clone = new ArrayList<Integer>(tem);            res.add(clone);            return;        }                ArrayList<Integer> cache = new ArrayList<Integer>();        for(int i=0; i<num.length; i++) {            if(!cache.contains(num[i])) {                cache.add(num[i]);                int[] nextNum = new int[num.length-1];                int nextLen = 0;                for(int j=0; j<num.length; j++) {                    if(j!=i) nextNum[nextLen++] = num[j];                }                tem.add(num[i]);                permuteUnique(nextNum, res, tem);                tem.remove(tem.size()-1);            }        }        return;    }        public ArrayList<ArrayList<Integer>> permuteUnique(int[] num) {        ArrayList<ArrayList<Integer>> res = new ArrayList<ArrayList<Integer>>();        ArrayList<Integer> tem = new ArrayList<Integer>();        permuteUnique(num, res, tem);        return res;    }}


0 0
原创粉丝点击