【919、带重复数字的全排列】

48 阅读1分钟
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class PermutationsWithDuplicates {
    public static List<List<Integer>> permuteUnique(int[] nums) {
        List<List<Integer>> result = new ArrayList<>();
        Arrays.sort(nums); // 对数组进行排序,以便处理重复数字
        
        boolean[] used = new boolean[nums.length];
        List<Integer> currentPermutation = new ArrayList<>();
        
        generatePermutations(nums, used, currentPermutation, result);
        
        return result;
    }
    
    private static void generatePermutations(int[] nums, boolean[] used, List<Integer> currentPermutation, List<List<Integer>> result) {
        if (currentPermutation.size() == nums.length) {
            result.add(new ArrayList<>(currentPermutation));
            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;
            currentPermutation.add(nums[i]);
            
            generatePermutations(nums, used, currentPermutation, result);
            
            used[i] = false;
            currentPermutation.remove(currentPermutation.size() - 1);
        }
    }
    
    public static void main(String[] args) {
        int[] nums = {1, 1, 2};
        List<List<Integer>> permutations = permuteUnique(nums);
        
        for (List<Integer> permutation : permutations) {
            System.out.println(permutation);
        }
    }
}