Skip to content

Instantly share code, notes, and snippets.

@shortthirdman
Created March 20, 2025 15:22
Show Gist options
  • Save shortthirdman/88ad4cc216b76d9b3fd845ff52e723ec to your computer and use it in GitHub Desktop.
Save shortthirdman/88ad4cc216b76d9b3fd845ff52e723ec to your computer and use it in GitHub Desktop.
Permute Unique Numbers
def permuteUnique(nums):
def backtrack(path, used):
if len(path) == len(nums):
result.append(path[:])
return
for i in range(len(nums)):
if used[i]:
continue
# Skip duplicates
if i > 0 and nums[i] == nums[i - 1] and not used[i - 1]:
continue
used[i] = True
path.append(nums[i])
backtrack(path, used)
path.pop()
used[i] = False
nums.sort() # Sort to handle duplicates
result = []
used = [False] * len(nums)
backtrack([], used)
return result
# Example usage
nums = [1, 1, 2]
print(permuteUnique(nums))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment