Topic
(https://leetcode-cn.com/problems/letter-combinations-of-a-phone-number/)
Problem analysis
Just get this question when there is no train of thought, can only follow the logic to think. Each number corresponds to three or four letters, which means we have three or four choices for each position. Then it seems that we can solve the problem with recursion, because the letters of each location need to make a variety of choices, and the next place to make this choice is the same. Well, let's write a recursive function based on this idea.
/* C++代码*//* ret 为储存最终结果的数组 map 是字母到数字的映射表 digits 是一串要转换数字 s 由数字转换成的字符串*/void fun(vector<string>& ret, const char map[8][5], const string& digits, string& s) { if (s.length() < digits.length()) { for (int i = 0; i < strlen(map[(digits[s.length()] - ‘0‘) - 2]); i++) { s.push_back(map[(digits[s.length()] - ‘0‘) - 2][i]); fun(ret,map,digits,s); s.pop_back(); } } else if (s.length() == digits.length()) { ret.push_back(s); }}
Some friends may find that this is a depth-first search process, then congratulations, the content will be very easy to understand, if not reflected, there are pictures behind to help understand.
Part of the execution of this function is seen (in fact, drawing too much bother to draw the whole process, it is not necessary), after reading it should be easier to understand.
Because eventually we're going to return an array to Leetcode, with a function on the outer sleeve
/* C++代码*/vector<string> letterCombinations(string digits) { vector<string> ret; if (digits.length() == 0) { return ret; } char map[8][5] = { {‘a‘,‘b‘,‘c‘,0}, {‘d‘,‘e‘,‘f‘,0}, {‘g‘,‘h‘,‘i‘,0}, {‘j‘,‘k‘,‘l‘,0}, {‘m‘,‘n‘,‘o‘,0}, {‘p‘,‘q‘,‘r‘,‘s‘,0}, {‘t‘,‘u‘,‘v‘,0}, {‘w‘,‘x‘,‘y‘,‘z‘,0} }; string s; fun(ret, map, digits, s); return ret; }
Time complexity O (4^n), Spatial complexity O (n).
Letter combination of Leetcode phone number