flag
软件学院大三党,每天一道算法题,第二天
题目介绍
给定一个仅包含数字 2-9 的字符串,返回所有它能表示的字母组合。
给出数字到字母的映射如下(与电话按键相同)。注意 1 不对应任何字母。
示例:
输入:“23”
输出:[“ad”, “ae”, “af”, “bd”, “be”, “bf”, “cd”, “ce”, “cf”].
思路
(1)使用hashmap保存按键对应的字母信息
(2)使用回溯法
回溯是一种通过穷举所有可能情况来找到所有解的算法。如果一个候选解最后被发现并不是可行解,回溯算法会舍弃它,并在前面的一些步骤做出一些修改,并重新尝试找到可行解。
(3)给出如下回溯函数 backtrack(combination, next_digits) ,它将一个目前已经产生的组合 combination 和接下来准备要输入的数字 next_digits 作为参数。
①如果没有更多的数字需要被输入,那意味着当前的组合已经产生好了。
②如果还有数字需要被输入:
遍历下一个数字所对应的所有映射的字母。
将当前的字母添加到组合最后,也就是 combination = combination + letter 。
重复这个过程,输入剩下的数字: backtrack(combination + letter, next_digits[1:])
小tip
1 取字符串的前i个字符
str=str.Substring(0,i); or str=str.Remove(i,str.Length-i);
2 去掉字符串的前i个字符:
str=str.Remove(0,i); or str=str.Substring(i);
3 从右边开始取i个字符:
str=str.Substring(str.Length-i); or str=str.Remove(0,str.Length-i);
4 从右边开始去掉i个字符:
str=str.Substring(0,str.Length-i); or str=str.Remove(str.Length-i,i);
原文链接:https://blog.csdn.net/u010892253/article/details/54892676
关键代码
class Solution {
Map<String, String> phone ;//保存电话按键对应的字母
List<String> output;//保存结果字母串的列表
public Solution(){
phone = new HashMap<>();
phone.put("2", "abc");
phone.put("3", "def");
phone.put("4", "ghi");
phone.put("5", "jkl");
phone.put("6", "mno");
phone.put("7", "pqrs");
phone.put("8", "tuv");
phone.put("9", "wxyz");
output = new ArrayList<>();
}
public void backtrack(String combination, String next_digits) {
// 已计算到数字串的末位,此时数字串为空
if (next_digits.length() == 0) {
// 将该组合加入结果列表
output.add(combination);
}
// 数字串中还有数字
else {
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);
// 将当前组合串和去掉第一个字符的next_digits继续递归
backtrack(combination + letter, next_digits.substring(1));
}
}
}
public List<String> letterCombinations(String digits) {
if (digits.length() != 0)
backtrack("", digits);//初始串为空字符串
return output;
}
}
测试数据
Solution solution=new Solution();
List<String> l=solution.letterCombinations("233");
for(int i=0;i<l.size();i++){
System.out.println(l.get(i));
}
结果: