Problem description:

Given a digit string, return all possible letter combinations that the number could represent.

A mapping of digit to letters (just like on the telephone buttons) is given below.

Input:Digit string “23”
Output: [“ad”, “ae”, “af”, “bd”, “be”, “bf”, “cd”, “ce”, “cf”].

Solution:

This question is a relatively easy backtracking problem. The idea of backtracking is to find the end result of a branch, then move back one step and search for other results.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution {
public:
vector<string> dict{" ", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
vector<string> letterCombinations(string digits) {
vector<string> res;
string tmp= "";
helper(res, tmp, digits, 0);
return res;
}

void helper(vector<string>& res, string tmp, string& digits, int index){
if(index > digits.size()-1){
res.push_back(tmp);
return;
}
int num= digits[index]-'0';
for(auto c: dict[num]){
helper(res, tmp+c, digits, index+1);
}
}
};

reference:
https://goo.gl/o1acNw
https://goo.gl/HBP2MX