Permutations II

这个题和permutation很像,只是需要考虑重复的数字。重复的数字只有第一次出现的时候加入,保证永远都是第一个重复出现的数字在前,而且要加过(用used数组纪律的时候,重复数字第一个如果没有被mark,就应该跳过)。

class Solution {
    /**
     * @param nums: A list of integers.
     * @return: A list of unique permutations.
     */
    public ArrayList<ArrayList<Integer>> permuteUnique(ArrayList<Integer> nums) {
        // write your code here
        ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();
        if(nums.size() == 0 || nums == null){
            return result;
        }
        ArrayList<Integer> list = new ArrayList<Integer>();
        Collections.sort(nums);
        permuteUniqueHelper(result, list, nums, new boolean[nums.size()]);
        return result;
    }
    
    private void permuteUniqueHelper(ArrayList<ArrayList<Integer>> result,
                                     ArrayList<Integer> list,
                                     ArrayList<Integer> nums,
                                     boolean[] used){
        if (list.size() == nums.size()){
            result.add(new ArrayList<Integer>(list));
        }          
        for(int i = 0; i < nums.size(); i++){
            if(used[i] || (i >0 && nums.get(i-1) == nums.get(i) && !used[i-1])){
                /* the only way that the later one is being added IS the pervious one has been add, 
                so this is the first time of such combination. 
                */
                continue;
            }
            used[i] = true;
            list.add(nums.get(i));
            permuteUniqueHelper(result, list, nums, used);
            list.remove(list.size() - 1);
            used[i] = false;
        }
    }
}

 

posted on 2016-08-18 08:05  codingEskimo  阅读(116)  评论(0编辑  收藏  举报

导航