【LeetCode】#47全排列II(Permutations II)

【LeetCode】#47全排列II(Permutations II)

题目描述

给定一个可包含重复数字的序列,返回所有不重复的全排列。

示例

输入: [1,1,2]
输出:
[
[1,1,2],
[1,2,1],
[2,1,1]
]

Description

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

解法

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

猜你喜欢

转载自blog.csdn.net/weixin_43858604/article/details/84851669