Letter combinations of a Phone number
Given a digit string, return all possible letter combinations, the number could represent.
A mapping of Digit to letters (just as on the telephone buttons) is given below.
Input: Digit string "Output": ["Ad", "AE", "AF", "BD", "Be", "BF", "CD", "CE", "CF"].
Note:
Although the above answer is in lexicographical order, your answer could are in any order you want.
Problem Solving Ideas:
Backtracking method. Backtracking by recursion. The code is as follows. Here's a trick to record the possible letters of each number through an array. In addition, when passing parameters, the character pointer points to the current scan character, and the transfer efficiency is faster. The following code is only 2ms efficient in Leetcode.
Class Solution {public: vector<string> lettercombinations (string digits) { string letters[] = {"", "", " ABC "," Def "," Ghi "," JKL "," MnO "," PQRS "," TUV "," WXYZ "}; vector<string> result; char * c = (char*) digits.c_str (); Getletters (Result, "", c, letters); return result; } void Getletters (vector<string>& result, string s, char* C, string letters[]) { if (*c = = ')} { if (s!= "" ) Result.push_back (s); } else{ String letter = Letters[*c-' 0 ']; int len = Letter.length (); for (int i=0;i<len; i++) { getletters (result, S + letter[i], c+1, Letters);}}} ;
[Leetcode] Letter combinations of a Phone number