首页 > 其他 > 详细

Permutations II

时间:2016-08-18 08:40:19      阅读:234      评论:0      收藏:0      [点我收藏+]

这个题和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;
        }
    }
}

 

Permutations II

原文:http://www.cnblogs.com/codingEskimo/p/5782585.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!