Algo-Sim › Recursion & Backtracking

Permutations II

Medium · Recursion & Backtracking · step through it in Java, Python and C++ on your own input

Every distinct ordering when values repeat: sort, then skip a value whose equal twin to the left is still unused.

Problem

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

Constraints

Edge cases to test

Follow-up questions

Why skip when the left twin is unused?
It forces equal values to appear in left-to-right order, so each distinct arrangement is built once.
What is the counting alternative?
Backtrack over a count map of distinct values instead of positions: the same output with no sort or skip rule.

Solution

Java

List<List<Integer>> result = new ArrayList<>();

List<List<Integer>> permuteUnique(int[] nums) {
    Arrays.sort(nums);
    backtrack(nums, new boolean[nums.length], new ArrayList<>());
    return result;
}

void backtrack(int[] nums, boolean[] used, List<Integer> path) {
    if (path.size() == nums.length) {
        result.add(new ArrayList<>(path));
        return;
    }
    for (int i = 0; i < nums.length; i++) {
        if (used[i]) continue;
        // A twin that is still unused means this value was already tried here.
        if (i > 0 && nums[i] == nums[i - 1] && !used[i - 1]) continue;
        used[i] = true;
        path.add(nums[i]);
        backtrack(nums, used, path);
        path.remove(path.size() - 1);
        used[i] = false;
    }
}

Python

def permute_unique(nums):
    nums = sorted(nums)
    result = []
    used = [False] * len(nums)

    def backtrack(path):
        if len(path) == len(nums):
            result.append(path[:])
            return
        for i in range(len(nums)):
            if used[i]:
                continue
            # A twin that is still unused means this value was already tried here.
            if i > 0 and nums[i] == nums[i - 1] and not used[i - 1]:
                continue
            used[i] = True
            path.append(nums[i])
            backtrack(path)
            path.pop()
            used[i] = False

    backtrack([])
    return result

C++

#include <bits/stdc++.h>
using namespace std;

class Solution {
  public:
    vector<vector<int>> result = {};

    vector<vector<int>> permuteUnique(vector<int> &nums) {
        sort(nums.begin(), nums.end());
        vector<int> path;
        vector<bool> used(nums.size());
        backtrack(nums, used, path);
        return result;
    }

    void backtrack(vector<int> &nums, vector<bool> &used, vector<int> &path) {
        if (int(path.size()) == int(nums.size())) {
            result.push_back(path);
            return;
        }
        for (int i = 0; i < int(nums.size()); i++) {
            if (used[i])
                continue;
            // A twin that is still unused means this value was already tried here.
            if (i > 0 && nums[i] == nums[i - 1] && !used[i - 1])
                continue;
            used[i] = true;
            path.push_back(nums[i]);
            backtrack(nums, used, path);
            path.pop_back();
            used[i] = false;
        }
    }
};

More Recursion & Backtracking problems