17. Letter Combinations of a Phone Number

题目:
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"].

类似于手机输入法,输入一串数字,列出所有可能的字母情况

思路:

感觉这题也没什么方法啥的,完全就是考验STL特别是MAP的使用,还有一些逻辑能力?我这完全暴力的方法居然就是最优了,当然大家也都是这样的

vector<string> letterCombinations(string digits) {
	int sz = digits.size(), tvsz;
	if (sz == 0)
		return vector<string>();
	map<char, vector<char>> dic; 
	vector<char>  tv;
	vector<string> res, tres;
	res.push_back(string());
	string ts;
	
	dic.insert(pair<char, vector<char>>('1', {}));
	dic.insert(pair<char, vector<char>>('2', {'a','b','c'}));
	dic.insert(pair<char, vector<char>>('3', {'d','e','f'}));
	dic.insert(pair<char, vector<char>>('4', {'g','h','i'}));
	dic.insert(pair<char, vector<char>>('5', {'j','k','l'}));
	dic.insert(pair<char, vector<char>>('6', {'m','n','o'}));
	dic.insert(pair<char, vector<char>>('7', {'p','q','r','s'}));
	dic.insert(pair<char, vector<char>>('8', {'t','u','v'}));
	dic.insert(pair<char, vector<char>>('9', {'w','x','y','z'}));
	
	for (int i = 0; i < sz; ++i) {
		int ressz = res.size();
		tres.clear();
		tv = dic[digits[i]];
		tvsz = tv.size();
		for (int j = 0; j < ressz; ++j) {
			ts = res[j];
			for (int z = 0; z < tvsz; ++z) {
				tres.push_back(ts + tv[z]);
			}
		}
		res = tres;
	}
	return res;
}
全部评论

相关推荐

蚂蚁 基架java (n+6)*16 签字费若干
点赞 评论 收藏
分享
无情咸鱼王的秋招日记之薛定谔的Offer:好拒信,偷了,希望有机会用到
点赞 评论 收藏
分享
评论
点赞
收藏
分享
牛客网
牛客企业服务