17、电话号码的字母组合

给定一个仅包含数字 2-9 的字符串,返回所有它能表示的字母组合。

给出数字到字母的映射如下(与电话按键相同)。注意 1 不对应任何字母。

图中显示:2:abc; 3:def; 4:ghi; 5:jkl; 6:mno; 7:pqrs; 8:tuv; 9:wxyz;

输入:"23"

输出:["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].

方法一:动态规划

思路:

【1】对于“​456”字符串,若我们已经知道”45“对应的字符串str

【2】再添加”6“的话,只需在str后面添加”6“所对应的字符种类

【3】结束条件为str的长度等于输入字符串digits的长度,说明已经完成当前组合​​

vector<string> vec = { "abc","def","ghi","jkl","mno","pqrs","tuv","wxyz" };	
vector<string> ans;
//str为当前字符串,index为digis字符的下标
void dpCombination(string str, int index, string digits) {
	if (str.length() == digits.length()) {
		ans.push_back(str);
	}
	else {
		int temp = digits[index] - '0' - 2;    //对应vec的下标,例字符'2'对应的是数组下标0
		for (int i = 0;i < vec[temp].size();++i) {    //对字符串添加上当前字符种类,并向下递归
			dpCombination(str + vec[temp][i], index + 1, digits);
		}
	}
}

vector<string> letterCombinations(string digits) {
	if (digits.size() == 0)
		return ans;
	string str = "";
	dpCombination(str, 0, digits);
	return ans;
}

猜你喜欢

转载自blog.csdn.net/hello_noob/article/details/89811243