Created
March 20, 2025 15:22
-
-
Save shortthirdman/88ad4cc216b76d9b3fd845ff52e723ec to your computer and use it in GitHub Desktop.
Permute Unique Numbers
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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