Permutations II
LeetCode 47 | Difficulty: Mediumβ
MediumProblem 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.
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?
Grouping, finding closest pairs, interval problems, enabling two-pointer or binary search.
Solutionsβ
Solution 1: C# (Best: 551 ms)β
| Metric | Value |
|---|---|
| Runtime | 551 ms |
| Memory | N/A |
| Date | 2018-01-22 |
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β
| Approach | Time | Space |
|---|---|---|
| Backtracking | ||
| Sort + Process |
Interview Tipsβ
- Discuss the brute force approach first, then optimize. Explain your thought process.
- Identify pruning conditions early to avoid exploring invalid branches.