Skip to main content

Command Palette

Search for a command to run...

permuation 1

Published
1 min readView as Markdown
import java.util.*;

public class Solution {
    public List<List<Integer>> permuteUnique(int[] nums) {
        List<List<Integer>> result = new ArrayList<>();

        // Sort to handle duplicates
        Arrays.sort(nums);

        boolean[] used = new boolean[nums.length];
        backtrack(nums, new ArrayList<>(), used, result);

        return result;
    }

    private void backtrack(int[] nums, List<Integer> temp, boolean[] used, List<List<Integer>> result) {
        if (temp.size() == nums.length) {
            result.add(new ArrayList<>(temp));
            return;
        }

        for (int i = 0; i < nums.length; i++) {
            // Skip if already used in this path
            if (used[i]) continue;

            // Skip duplicates: If it's same as previous and previous wasn't used, skip
            if (i > 0 && nums[i] == nums[i - 1] && !used[i - 1]) continue;

            temp.add(nums[i]);
            used[i] = true;

            backtrack(nums, temp, used, result);

            // Backtrack
            temp.remove(temp.size() - 1);
            used[i] = false;
        }
    }
}

More from this blog

Amit singh's blog

235 posts