LeetCode 47. Permutations II 全排列II(Java)

题目:

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

Example:
Input: [1,1,2]
Output:
[
[1,1,2],
[1,2,1],
[2,1,1]
]

解答:

本题与上一题相似,采用递归,这道题原数组 nums 中包含重复数,所以采用 Arrays.sort() 排序后,增加数组 flags 作为标志位,便于进行去重判断

class Solution {
    public List<List<Integer>> permuteUnique(int[] nums) {
        Arrays.sort(nums);
        List<List<Integer>> res = new ArrayList<>();
        List<Integer> list = new ArrayList<>();
        boolean[] flags = new boolean[nums.length];
        recursion(res, list, nums, flags);
        return res;
    }
    private void recursion(List<List<Integer>> res, List<Integer> list, int[] nums, boolean[] flags) {
        if(list.size() == nums.length) {
            res.add(new ArrayList<>(list));
            return;
        }
        for(int i=0; i<nums.length; i++) {
            if(i>0 && nums[i]==nums[i-1] && flags[i-1]==false) {
                continue;
            }
            if(flags[i]==false) {
                flags[i]=true;
                list.add(nums[i]);
                recursion(res, list, nums, flags);
                flags[i]=false;
                list.remove(list.size()-1);                
            }
        }
    }
}

你可能感兴趣的:(LeetCode)