17. Letter Combinations of a Phone Number

Given a string containing digits from 2-9 inclusive, 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. Note that 1 does not map to any letters.

Example:

Input: "23"
Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].

思考:按照如下图进行遍历。以输入为“234”为例。
 
 1 class Solution {
 2 public:
 3     vector<string> letterCombinations(string digits) {
 4         vector<string> res;
 5         if(digits.size()==0) return res;
 6         
 7         string map[] = {" ", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
 8         string comb(digits.size(),'');
 9         recursion(digits, 1, comb, res,map);
10         return res;
11     }
12     void recursion(string &digits, int len, string &comb, vector<string> &res, string map[]) {
13         if(len==digits.size()+1) {
14             res.push_back(comb);
15             return;
16         }
17         
18         string letters = map[digits[len-1] - '0'];
19         for(int j=0; j<letters.size(); j++) {
20             comb[len-1] = letters[j];
21             recursion(digits, len+1, comb, res,map);
22         }
23     }
24 };
原文地址:https://www.cnblogs.com/midhillzhou/p/8873210.html