17. 电话号码的字母组合

题目

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

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

Alt
**示例:**输入:“23”
输出:[“ad”, “ae”, “af”, “bd”, “be”, “bf”, “cd”, “ce”, “cf”].

1 深度优先的回溯方法

回溯是一种通过穷举所有可能情况来找到所有解的算法。如果一个候选解最后被发现并不是可行解,回溯算法会舍弃它,并在前面的一些步骤做出一些修改,并重新尝试找到可行解。

给出如下回溯函数 backtrack(combination, next_digits) ,它将一个目前已经产生的组合 combination 和接下来准备要输入的数字 next_digits 作为参数。

如果没有更多的数字需要被输入,那意味着当前的组合已经产生好了。
如果还有数字需要被输入:
遍历下一个数字所对应的所有映射的字母。
将当前的字母添加到组合最后,也就是 combination = combination + letter 。
重复这个过程,输入剩下的数字: backtrack(combination + letter, next_digits[1:]) 。

作者:LeetCode
链接:https://leetcode-cn.com/problems/letter-combinations-of-a-phone-number/solution/dian-hua-hao-ma-de-zi-mu-zu-he-by-leetcode/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

class Solution {
  Map<String, String> phone = new HashMap<String, String>() {{
    put("2", "abc");
    put("3", "def");
    put("4", "ghi");
    put("5", "jkl");
    put("6", "mno");
    put("7", "pqrs");
    put("8", "tuv");
    put("9", "wxyz");
  }};

  List<String> output = new ArrayList<String>();

  public void backtrack(String combination, String next_digits) {
    // if there is no more digits to check
    if (next_digits.length() == 0) {
      // the combination is done
      output.add(combination);
    }
    // if there are still digits to check
    else {
      // iterate over all letters which map 
      // the next available digit
      String digit = next_digits.substring(0, 1);
      String letters = phone.get(digit);
      for (int i = 0; i < letters.length(); i++) {
        String letter = phone.get(digit).substring(i, i + 1);
        // append the current letter to the combination
        // and proceed to the next digits
        backtrack(combination + letter, next_digits.substring(1));
      }
    }
  }

  public List<String> letterCombinations(String digits) {
    if (digits.length() != 0)
      backtrack("", digits);
    return output;
  }
}

作者:LeetCode
链接:https://leetcode-cn.com/problems/letter-combinations-of-a-phone-number/solution/dian-hua-hao-ma-de-zi-mu-zu-he-by-leetcode/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

2 广度优先的队列方法

方法概述:
利用数据结构中队列的“先进先出”的知识,采用实时更新队列的内容实现遍历。
步骤说明:
1.建立一个map哈希表;
2.新建一个队列;
3.将第一个字符串所对应的码表逐步进入到队列中;
4.出队操作,存储当前出队的string;
5.将此string与后一个字符串所对应的码表中每一个值相加并逐步进入到队列中;
6.最终队列中存储的即为所有情况的string

class Solution {
public:
    vector<string> letterCombinations(string digits) {
        vector<string> res;//用于输出向量
		map<char, string> m = { {'2',"abc" },{'3',"def"},{'4',"ghi"},{'5',"jkl"},{'6',"mno"},{'7',"pqrs"},{'8',"tuv"},{'9',"wxyz"} };//映射map哈希表
		int size = digits.size();//输入字符串产长度
		queue<string> que;//新建队列
		
		//先将第一个元素对应的码表入队
		for (int j = 0; j < m[digits[0]].size(); j++)
		{
			string str;
			str.push_back(m[digits[0]][j]);//char转string
			que.push(str);//string入队
		}
		string s;//用于存储队头元素
		for (int i = 1; i < size; i++)
		{
			int length = que.size();//当前队列长度
			while (length--)
			{
				for (int j = 0; j < m[digits[i]].size(); j++)
				{
					s = que.front();
					s = s + m[digits[i]][j];//队头元素加上新元素
					que.push(s);//入队
				}
				que.pop();//队头出队
			}
		}
		while (!que.empty())
		{
			res.push_back(que.front());//队头元素存储至res
			que.pop();//队头出队
		}
		return res;//返回

    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
问题:给定一个仅包含数字 2-9 的字符串,返回所有它能表示的字母组合。给出数字到字母的映射和一个数字字符串,按按键顺序给出所有可能的字母组合。 根据题目要求,我们可以使用回溯算法来解决该问题。 具体算法步骤如下: 1. 定义一个映射表,将数字与字母的映射关系存储起来。 2. 定义一个结果列表,用于存储所有可能的字母组合。 3. 定义一个递归函数 backtracking,用于生成所有可能的字母组合。 - 递归函数参数包括当前生成的字母组合 combination、剩余待处理的数字字符串 digits 和当前处理的层数 level。 - 如果当前处理的层数等于数字字符串的长度,将当前生成的字母组合添加到结果列表中,并返回。 - 否则,获取当前层对应的数字,并依次取出映射的字母。 - 对于每个字母,将字母加入到当前生成的字母组合中,并递归调用 backtracking 函数处理下一层。 - 处理完毕后,将当前加入的字母移除,进行下一轮循环。 4. 调用递归函数 backtracking,传入初始的字母组合为空串,剩余待处理的数字字符串为给定数字字符串,层数初始值为 0。 5. 返回结果列表。 算法实现如下: ```python def letterCombinations(digits): if digits == "": return [] mapping = { '2': 'abc', '3': 'def', '4': 'ghi', '5': 'jkl', '6': 'mno', '7': 'pqrs', '8': 'tuv', '9': 'wxyz' } result = [] def backtracking(combination, digits, level): if level == len(digits): result.append(combination) return letters = mapping[digits[level]] for letter in letters: backtracking(combination + letter, digits, level + 1) backtracking("", digits, 0) return result ``` 测试样例: ```python print(letterCombinations("23")) # ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"] print(letterCombinations("")) # [] print(letterCombinations("2")) # ["a", "b", "c"] ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值