Iam_Sandeep

Permutation of a string backtracking

May 13th, 2022 (edited)
777
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.70 KB | None | 0 0
  1. #Method 1: It includes even duplicates
  2. #Better to go to method 2
  3. def permute(s):
  4.     s=list(s)
  5.     n,ans=len(s),[]
  6.     def dfs(i):
  7.         if i==n-1:
  8.             ans.append(''.join(s))
  9.             return
  10.         # we will swap indices from i+1 to n with i and do backtrack. This ensures generations of diff permutatations
  11.         #In recursion level 1 we do swapping from 0th index to  (0+1,n) indices
  12.         #in recursion level 2 we do swapping from 1st index to (1+1,n) indices
  13.         #in recursion level ith we do swaping from ith index to (i+1,n) indices
  14.         for j in range(i+1,n):
  15.             s[i],s[j]=s[j],s[i]
  16.             dfs(i+1)
  17.             s[i],s[j]=s[j],s[i]
  18.     dfs(0)
  19.     return ans
  20. permute("shpdwa")
  21. #Method 2:No duplicates
  22. '''
  23. Why this works.
  24. Since hashmap stores multiple counts of single same character.
  25. So all keys in dict are unique.
  26. When we do backtracking with these keys we can avoid duplicates.
  27. E.g. (1,1) without hashmap it creates 2 partitions (1,1)(1,1)
  28. But dictionary has {1:2}
  29. keys=(1) . so only one pemutation happens
  30. try with one more e.g. (1,2,2) you can understand easily
  31. '''
  32. class Solution:
  33.     def permuteUnique(self, nums: List[int]) -> List[List[int]]:
  34.         freq={}
  35.         res=[]
  36.         perm=[]
  37.         for i in nums:
  38.             freq[i]=freq.get(i,0)+1
  39.         def dfs():
  40.             if len(perm)==len(nums):
  41.                 res.append(perm[:])
  42.                 return
  43.             else:
  44.                 for key in freq.keys():
  45.                     if freq[key]>0:
  46.                         freq[key]-=1
  47.                         perm.append(key)
  48.                         dfs()
  49.                         perm.pop()
  50.                         freq[key]+=1
  51.             return res
  52.         return dfs()
  53.                    
  54.                        
  55.    
  56.        
Add Comment
Please, Sign In to add comment