Advertisement
mhr007

Untitled

Oct 25th, 2021
37
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.47 KB | None | 0 0
  1. #https://leetcode.com/problems/letter-combinations-of-a-phone-number
  2. class Solution:
  3. combination = []
  4. def backtrack(self,arr,pos,level,current,t,digits):
  5.  
  6. if level >= t:
  7. return
  8.  
  9.  
  10. if pos >= len(arr[digits[level]-2]):
  11. return
  12.  
  13.  
  14.  
  15.  
  16. current.append(arr[digits[level]-2][pos])
  17. self.backtrack(arr,0,level+1,current,t,digits)
  18.  
  19. if level == t-1:
  20. self.combination.append(current.copy())
  21.  
  22. current.pop(-1)
  23. self.backtrack(arr,pos+1,level,current,t,digits)
  24. current =[]
  25. return
  26.  
  27.  
  28. def letterCombinations(self, digits: str) -> List[str]:
  29.  
  30. # 2,3 -> ad,ae,af,bd,be,bf,cd,ce,cf
  31. self.combination = []
  32.  
  33. let = {
  34. 0 : "abc",
  35. 1 : "def",
  36. 2 : "ghi",
  37. 3 : "jkl",
  38. 4 : "mno",
  39. 5 : "pqrs",
  40. 6 : "tuv",
  41. 7 : "wxyz"
  42. }
  43.  
  44. digits = [int(a) for a in digits]
  45.  
  46.  
  47. current = []
  48. pos = 0
  49. level = 0
  50. self.backtrack(arr=let,pos=pos,level=level,current=current,t=len(digits),digits=digits)
  51.  
  52.  
  53. # print([ "".join(x) for x in self.combination])
  54.  
  55. #print(self.combination)
  56.  
  57.  
  58. return [ "".join(x) for x in self.combination]
  59.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement