Advertisement
imashutosh51

Letter Combination of a phone number

Oct 16th, 2022 (edited)
62
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.33 KB | None | 0 0
  1. void fun(string digits,unordered_map<char,string> mp,vector<string> &ans,string cur,int i,int n){
  2.      if(i<n){
  3.          for(int k=0;k<mp[digits[i]].size();k++){
  4.             fun(digits,mp,ans,cur+mp[digits[i]][k],i+1,n);
  5.          }
  6.      }
  7.      else{
  8.          ans.push_back(cur);
  9.          return;
  10.      }
  11. }
  12.  
  13. class Solution {
  14. public:
  15.     vector<string> letterCombinations(string digits) {
  16.         vector <string> ans;
  17.         if(digits.size()==0) return ans;
  18.         unordered_map<char,string> mp;
  19.         mp['2']="abc";
  20.         mp['3']="def";
  21.         mp['4']="ghi";
  22.         mp['5']="jkl";
  23.         mp['6']="mno";
  24.         mp['7']="pqrs";
  25.         mp['8']="tuv";
  26.         mp['9']="wxyz";
  27.        
  28.         fun(digits,mp,ans,"",0,digits.size());
  29.         return ans;
  30.     }
  31. };
  32.  
  33. #Python
  34. ans=[]
  35. def fun(st,i,cur):
  36.     print(i,len(st))
  37.     global ans;
  38.     dict={'2':'abc','3':'def','4':'ghi','5':'jkl','6':'mno','7':'pqrs','8':'tuv','9':'wxyz'}
  39.     if i==len(st):
  40.         ans.append(cur)
  41.         return
  42.     else:
  43.         temp=dict[st[i]]
  44.         for k in range(len(temp)):
  45.             fun(st,i+1,cur+temp[k])
  46.  
  47. class Solution:
  48.     def letterCombinations(self, digits: str) -> List[str]:
  49.         if len(digits)==0:
  50.             return []
  51.         global ans;
  52.         ans=[]
  53.         fun(digits,0,'')
  54.         return ans;
  55.        
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement