LeetCode 0047. Permutations II Solution in Java, Python, C++, JavaScript, Go & Rust | Explanation + Code

CoderIndeed
0
0047. Permutations II

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

Solutions

Solution 1: Sorting + Backtracking

We can first sort the array so that duplicate numbers are placed together, making it easier to remove duplicates.

Then, we design a function dfs(i), which represents the current number to be placed at the i-th position. The specific implementation of the function is as follows:

  • If i = n, it means we have filled all positions, add the current permutation to the answer array, and then return.
  • Otherwise, we enumerate the number nums[j] for the i-th position, where the range of j is [0, n - 1]. We need to ensure that nums[j] has not been used and is different from the previously enumerated number to ensure that the current permutation is not duplicated. If the conditions are met, we can place nums[j] and continue to recursively fill the next position by calling dfs(i + 1). After the recursive call ends, we need to mark nums[j] as unused to facilitate subsequent enumeration.

In the main function, we first sort the array, then call dfs(0) to start filling from the 0th position, and finally return the answer array.

The time complexity is O(n × n!), and the space complexity is O(n). Here, n is the length of the array. We need to perform n! enumerations, and each enumeration requires O(n) time to check for duplicates. Additionally, we need a marker array to mark whether each position has been used, so the space complexity is O(n).

Similar problems:

PythonJavaC++GoTypeScriptRustJavaScriptC#
class Solution: def permuteUnique(self, nums: List[int]) -> List[List[int]]: def dfs(i: int): if i == n: ans.append(t[:]) return for j in range(n): if vis[j] or (j and nums[j] == nums[j - 1] and not vis[j - 1]): continue t[i] = nums[j] vis[j] = True dfs(i + 1) vis[j] = False n = len(nums) nums.sort() ans = [] t = [0] * n vis = [False] * n dfs(0) return ans(code-box)

Post a Comment

0Comments

Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Check Now
Accept !