Skip to main content

Permutations II

LeetCode 47 | Difficulty: Medium​

Medium

Problem Description​

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

Example 1:

Input: nums = [1,1,2]
Output:
[[1,1,2],
[1,2,1],
[2,1,1]]

Example 2:

Input: nums = [1,2,3]
Output: [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]

Constraints:

- `1 <= nums.length <= 8`

- `-10 <= nums[i] <= 10`

Topics: Array, Backtracking, Sorting


Approach​

Backtracking​

Explore all candidates by building solutions incrementally. At each step, choose an option, explore further, then unchoose (backtrack) to try the next option. Prune branches that can't lead to valid solutions.

When to use

Generate all combinations/permutations, or find solutions that satisfy constraints.

Sorting​

Sort the input to bring related elements together or enable binary search. Consider: does sorting preserve the answer? What property does sorting give us?

When to use

Grouping, finding closest pairs, interval problems, enabling two-pointer or binary search.


Solutions​

Solution 1: C# (Best: 551 ms)​

MetricValue
Runtime551 ms
MemoryN/A
Date2018-01-22
Solution
public class Solution {
public IList<IList<int>> PermuteUnique(int[] nums) {
List<IList<int>> dp = new List<IList<int>>();
Array.Sort(nums);
bool[] used = new bool[nums.Length];
backtrack2(dp, new List<int>(), nums, used);
return dp;
}

public void backtrack2(List<IList<int>> dp, List<int> templist, int[] nums, bool[] used)
{
if (templist.Count == nums.Length)
{
dp.Add(templist.ToList());
}
else
{
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;
templist.Add(nums[i]);
backtrack2(dp, templist, nums, used);
used[i] = false;
templist.RemoveAt(templist.Count - 1);
}
}
}

}

Complexity Analysis​

ApproachTimeSpace
Backtracking$O(n! or 2^n)$$O(n)$
Sort + Process$O(n log n)$$O(1) to O(n)$

Interview Tips​

Key Points
  • Discuss the brute force approach first, then optimize. Explain your thought process.
  • Identify pruning conditions early to avoid exploring invalid branches.