본문 바로가기

개발 공부/Algorithm

Permute Practice

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]