題目
Given a digit string, 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.

Input: Digit string "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.
分析
由于不知道輸入的位數(shù),所以需要用深度優(yōu)點搜索。一開始想用棧來實現(xiàn),但是搞了半天腦子都糊掉了,最后還是乖乖用遞歸,順利完成。
實現(xiàn)
class Solution {
public:
vector<string> letterCombinations(string digits) {
vector<string> ans;
dfs(digits, 0, ans);
return ans;
}
private:
vector<string> character={"","","abc","def",
"ghi","jkl","mno",
"pqrs","tuv","wxyz"};
void dfs(string& digits, size_t cur, vector<string>& ans, string tmp=""){
if(cur>=digits.size()){
if(tmp.size()>0) ans.push_back(tmp);
return;
}
for(auto it: character[digits[cur]-'0']){
dfs(digits, cur+1, ans, tmp+it);
}
}
};
思考
遞歸的時候注意盡量不要傳遞復(fù)雜的數(shù)據(jù)結(jié)構(gòu)。使用引用加上索引會比較快。