【Leetcode】Letter Combinations of a Phone Number

本文详细阐述了如何通过递归算法将数字字符串转换为对应的字母组合,特别关注了特殊数字如9和7的处理方式。

问题

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.


代码

void myletterCombinations(const char *s , vector<string> &v , string currentString)
{
	if (!s) {
		return;
	}
	
	if (*s != '\0') {
		char testA[12];
		char a = ('a' + ((*s-'2') * 3));
		//sprintf(testA, "%c" , a + 4);
		/* get next */
		switch (*s) {
			case '9':
				myletterCombinations(s + 1, v, currentString + string("w"));
				myletterCombinations(s + 1, v, currentString + string("x"));
				myletterCombinations(s + 1, v, currentString + string("y"));
				myletterCombinations(s + 1, v, currentString + string("z"));
				break;
			case '8':
				myletterCombinations(s + 1, v, currentString + string("t"));
				myletterCombinations(s + 1, v, currentString + string("u"));
				myletterCombinations(s + 1, v, currentString + string("v"));
				break;
			case '7':
				myletterCombinations(s + 1, v, currentString + string("p"));
				myletterCombinations(s + 1, v, currentString + string("q"));
				myletterCombinations(s + 1, v, currentString + string("r"));
				myletterCombinations(s + 1, v, currentString + string("s"));
				break;
			case '6':
			case '5':
			case '4':
			case '3':
			case '2':
			{
				sprintf(testA, "%c" , a);
				myletterCombinations(s + 1, v, currentString + string(testA));
				sprintf(testA, "%c" , a+1);
				myletterCombinations(s + 1, v, currentString + string(testA));
				sprintf(testA, "%c" , a +2);
				myletterCombinations(s + 1, v, currentString + string(testA));
				break;
			}
			default:
				myletterCombinations(s + 1, v, currentString);
				break;
		}
	}
	else{
		v.push_back(currentString);
	}
	
}

class Solution {
public:
    vector<string> letterCombinations(string digits) {
        vector<string> ss;
		myletterCombinations(digits.c_str(), ss, string(""));
		return ss;
    }
};

分析

这里注意不仅仅是 9 有四个字符,7也是,我开始没注意。 2-6 是没问题的,使用通用的算法计算就可以了。 7,9 不行,8自然在中间也不能独自计算。

递归之就行了。跳过了 0 , 1, #,* 等无意义的输入,我没有试过假设不处理这几个字符是否会拒绝我的代码。

总结

递归各种组合。递归之前想好递归的停止条件是啥。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值