leetcode --电话号码的字符组合(地平线面试题)

  1. 题目描述
    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.

每一种可能情况下有有多种可能,要求列出所有可能情况或者找最优的情况,递归是最简单的。这里的n中可能情况,每种可能下又有m中,就像一棵树一样,十分类似走迷宫的情况*(4中可能)。有的时候还不知道树的层数,这种就必须递归了。

class Solution {
public:
	vector<string> letterCombinations(string digits) {
		vector<string> codes = { "","","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz" };
		vector<string> ret;

		if (digits.empty())
			return ret;
		combination(digits, 0, "", ret, codes);
		return ret;

	}
	void combination(string digits, int pos, string base, vector<string> &ret, const vector<string>& codes)
	{
		if (pos == digits.length())
		{
			ret.push_back(base);
			return;
		}
		for (int i = 0; i < codes[digits[pos] - '0'].size(); i++)
		{
			combination(digits, pos + 1, base + codes[digits[pos] - '0'][i], ret, codes);
		}
	}
};

改编版:
规则改变:2连续按两次是‘b’,按三次是’c’,所以给出‘222’时的可能字符组合是aaa,ab,ba,c。

class Solution {
public:
	vector<string> letterCombinations(string digits) {
		vector<string> codes = { "0","1","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz" };
		vector<string> ret;

		if (digits.empty())
			return ret;
		combination(digits, 0, "", ret, codes);
		return ret;

	}
	void combination(string digits, int pos, string base, vector<string> &ret, const vector<string>& codes)
	{
		if (pos == digits.length())
		{
			ret.push_back(base);
			return;
		}
		//只需要在这里改变一下,首先算出连续字符的数目,然后列出所有可能情况。
		int num = 0;
		while (pos + num < digits.length() && digits[num + pos] == digits[pos])
			num++;
		for (int i = 1; i <= num; i++)
		{
			combination(digits, pos + i, base + codes[digits[pos]-'0'][i - 1], ret, codes);
		}
	}
};
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值