(好久不记录,但其实一直有缓慢的做,坚持不放弃,纯当记录一下思路,下次要边做题边写,每次做完题再来写就没感觉了。)
题目:
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:
分析:1.输入0和1怎么处理?
2.回溯算法
3.穷举
解决:
class Solution {
public:
map<char,string> dict;
void combin(int start,int end,string &digit,string cur,vector<string> &res){
if(start==end){
if(start==0)//输入为""时,保证输出的是[],而不是[""]。
return;
res.push_back(cur);
return;
}
for(int i=0;i<dict[digit[start]].size();++i)
combin(start+1,end,digit,cur+dict[digit[start]][i],res);
}
vector<string> letterCombinations(string digits) {
vector<string> result;
dict['2']="abc";
dict['3']="def";
dict['4']="ghi";
dict['5']="jkl";
dict['6']="mno";
dict['7']="pqrs";
dict['8']="tuv";
dict['9']="wxyz";
combin(0,digits.size(),digits,"",result);
return result;
}
};
利用了递归算法,其实我觉得这道题就是穷举法。
在编程的过程中,我默认输入不含0/1等特殊字符,但是如果是去面试,我在想是不是还是考虑全面更好呢???