Here's a C++ code that uses recursion to find all possible letter combinations of a phone number:
#include <iostream>
#include <vector>
#include <string>
using namespace std;
// Mapping of digits to corresponding letters
const vector<string> digitLetters = {
"", // 0
"", // 1
"abc", // 2
"def", // 3
"ghi", // 4
"jkl", // 5
"mno", // 6
"pqrs", // 7
"tuv", // 8
"wxyz" // 9
};
// Recursive function to find letter combinations
void findLetterCombinations(string digits, string current, vector<string>& result) {
// Base case: if there are no more digits, add the current combination to the result
if (digits.empty()) {
result.push_back(current);
return;
}
// Get the letters corresponding to the first digit
string letters = digitLetters[digits[0] - '0'];
// Recursively find combinations for the remaining digits
for (char letter : letters) {
findLetterCombinations(digits.substr(1), current + letter, result);
}
}
// Function to find letter combinations of a phone number
vector<string> letterCombinations(string digits) {
vector<string> result;
if (digits.empty()) {
return result;
}
findLetterCombinations(digits, "", result);
return result;
}
// Main function
int main() {
string phoneNumber = "23";
vector<string> combinations = letterCombinations(phoneNumber);
cout << "Letter combinations of phone number " << phoneNumber << ":" << endl;
for (string combination : combinations) {
cout << combination << endl;
}
return 0;
}
Output:
Letter combinations of phone number 23:
ad
ae
af
bd
be
bf
cd
ce
cf
Explanation:
The code utilizes recursion to explore all possible combinations of letters by iterating through the digits and their corresponding letters. It keeps track of the current combination formed at each step and adds it to the result vector when there are no more digits remaining. The process continues until all possible combinations are found.
153 videos|115 docs|24 tests
|
|
Explore Courses for Software Development exam
|