DSA - letter combinations of a phone number - C++,Dynamic Programming
Hey, so today we are going to solve Leetcode - letter combinations of a phone number
Problem Link- https://leetcode.com/problems/letter-combinations-of-a-phone-number/
class Solution {
public:
void solve(int start, string mapping[], string digits, vector<string>&ans, string s) {
if(start == digits.length()){
ans.push_back(s);
return;
}
int num= digits[start]-'0';
int val = mapping[num];
for(int i =0; i<val; i++){
s.push_back(val[i]);
solve(start+1, mapping, digits, ans, s);
s.pop_back();
}
}
vector<string> letterCombinations(string digits) {
vector<string> ans;
if(digits.length() == 0){
return ans;
}
int start = 0;
string s = "";
string mapping[10] = {"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
solve(start, mapping, digits, ans, s);
return ans;
}
}
Here's how the code works:
We define a function
letterCombinations
that takes a stringdigits
representing the phone number as input and returns a vector of strings containing all possible combinations of letters corresponding to the phone number.We first create a
mapping
vector that maps each digit to the corresponding set of letters on a phone keypad.We then call a helper function
solve
that takes thedigits
string, themapping
vector, thes
string that stores the current combination of letters being generated, and theans
vector that stores all valid combinations of letters generated so far.In the
solve
function, we check if thes
string has the same length as thedigits
string. If it does, then we have generated a valid combination of letters and add it to theans
vector.If the
s
string is not yet of the same length as thedigits
string, we get the current digit and its corresponding set of letters from themapping
vector, and iterate over all the letters in the set.For each letter, we add it to the
s
string, and recursively callsolve
with the updateds
string.After the recursive call returns, we remove the last letter added to
s
, and try the next letter in the set.Finally, in the
main
function, we callletterCombinations
with the phone numberdigits = "23"
, and print out all the valid combinations of letters returned by the function.