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.
Algorithm one: The combination of the thought of carrying the numeral.
Class Solution {public:vector<string> Lettercombinations (string digits) {const char *map[] = {"", "", " ABC "," Def "," Ghi "," JKL "," MnO "," PQRS "," TUV "," WXYZ "}; int idx[sizeof (map)/sizeof (map[0]) = {0}; vector<string> result; string item; BOOL carry = false; while (!carry) {item.clear (); carry = true; for (int i=0; i<digits.size (); ++i) {const char * p = &map[digits[i]-' 0 '][idx[i]]; if (*p) item.append (1, *p); if (carry && *p) {++idx[i]; ++p; if (!*p) idx[i] = 0; else carry = false; }} result.push_back (item); } if (Result.empty ()) Result.push_back (item); return result; }};
The following sentence is purely to satisfy the test case when the input of Leetcode is empty string (""):
if (Result.empty ()) result.push_back (item);
See this algorithm execution time, can not help to do a, leave a memorial.
Algorithm two, to be continued
Letter combinations of a Phone number--Leetcode