迭代和递归一直都是我的弱项(说的好像我有强项一样- - ) 不过迭代和递归感觉很多用在无法确定输出长度的时候。
就当作给自己记下来好了
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"].
Note:
Although the above answer is in lexicographical order, your answer could be in any order you want.
解析:
Initial state:
- result = {""}
Stage 1 for number "1":
- result has {""}
- candiate is "abc"
- generate three strings "" + "a", ""+"b", ""+"c" and put into tmp,
tmp = {"a", "b","c"} - swap result and tmp (swap does not take memory copy)
- Now result has {"a", "b", "c"}
Stage 2 for number "2":
- result has {"a", "b", "c"}
- candidate is "def"
- generate nine strings and put into tmp,
"a" + "d", "a"+"e", "a"+"f",
"b" + "d", "b"+"e", "b"+"f",
"c" + "d", "c"+"e", "c"+"f" - so tmp has {"ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf" }
- swap result and tmp
- Now result has {"ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf" }
vector<string> letterCombinations(string digits) { vector<string> res; if(digits.empty()) return vector<string>(); int len = (int)digits.length(); static const vector<string> map = {"","","abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"}; res.push_back(""); //这应该是一个迭代,好像递归和迭代经常用于不确定大小的东西 for(int i = 0 ; i < len; i++){ int num = digits[i] - '0'; if(num < 0 || num > 9) break; const string & candidate = map[num]; if(candidate.empty()) continue; vector<string>tmp; //每一个循环里面都新建了一个tmp,初始为空,突然觉得循环很像inline函数啊- - for(int j = 0; j < candidate.size(); j++) for(int k = 0; k < res.size(); k++) tmp.push_back(res[k] + candidate[j]); res.swap(tmp); } return res; }