-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathLetter Combinations of a Phone Number.cpp
36 lines (31 loc) · 1.37 KB
/
Letter Combinations of a Phone Number.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
// Problem Link : https://leetcode.com/problems/letter-combinations-of-a-phone-number/
vector<string> ans; // global variable
// ind == index for digits from which we will select a char
// curr == combination till now
void solve(string digits, int ind, unordered_map<char,string> mp, string curr){
// if we are at the end of string then add curr in ans as a possible combination and return
if(ind == digits.length()){
if(curr.length() > 0)
ans.push_back(curr);
return;
}
string str = mp[digits[ind]]; // we will take a single char from the string which can be access by the digits[ind]
for(int i = 0; i < str.length(); i++){ // one by one we will call every char from str and call for next ind in digits
solve(digits, ind+1, mp, curr+str[i]);
}
}
vector<string> letterCombinations(string digits) {
ans.clear(); // clearing previous answer
// adding all keys into the map
unordered_map<char,string> mp;
mp['2'] = "abc";
mp['3'] = "def";
mp['4'] = "ghi";
mp['5'] = "jkl";
mp['6'] = "mno";
mp['7'] = "pqrs";
mp['8'] = "tuv";
mp['9'] = "wxyz";
solve(digits,0,mp,""); // calling solve function that will fill the ans vector
return ans;
}