def permute(txt, src):
if src == len(txt):
return ["".join(txt)]
seen = set()
result = []
for i in range(src, len(txt)):
if txt[i] in seen:
continue
seen.add(txt[i])
if src!=i:
txt[src], txt[i] = txt[i], txt[src]
result.extend(permute(txt, src+1))
if src!=i:
txt[src], txt[i] = txt[i], txt[src]
return result
result = permute(lits(digits), 0)
- Base Case : When the src index equals the length of txt, it means the function has reached a complete permutation.
It returns the current permutation as a string inside a list.
if src == len(txt):
return ["".join(txt)]
- Avoiding Duplicate Permutations :
The seen set keeps track of characters already preocessed at the current src position. If acharacter has been processed, it skips to avoid generating duplicate permutations.
if txt[i] in seen:
continue
seen.add(txt[i])
- Swapping for Permutation:
To create permutations, the function swaps the character at src with the character at i. This rearranges the order.
if src!=i:
txt[src], txt[i] = txt[i], txt[src]
- Recursive Call and Backtracking:
After swapping, the function recursively generates permutations for the next position (src + 1),
After exploring all permutations for a particular arrangement, the function swaps back to restore the original order. This is necessary to explore other permutations.
result.extend(permute(txt, src+1))
if src!=i:
txt[src], txt[i] = txt[i], txt[src]
'개발 공부 > Algorithm' 카테고리의 다른 글
[LeetCode] 374. Guess Number Higher or Lower (0) | 2024.12.27 |
---|---|
[LeetCode] 62. Unique Paths (1) | 2024.12.15 |
[LeetCode] 17. Letter Combinations of a Phone Number (2) | 2024.12.13 |
[LeetCode] 2390. Removing Stars From a String (0) | 2024.12.10 |
[LeetCode] 338. Counting Bits (0) | 2024.12.10 |