Letter Combinations of a Phone Number

本文介绍了一种使用回溯法解决电话号码对应字母的所有可能组合的问题。通过递归地构建每一种可能的组合,并将它们存储在一个列表中。该算法利用了一个字符串数组来模拟电话键盘上每个数字对应的字母。
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.
[img]https://upload.wikimedia.org/wikipedia/commons/thumb/7/73/Telephone-keypad2.svg/200px-Telephone-keypad2.svg.png[/img]
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.

用一个字符串数组模拟键盘上数字代表的字符串,用回溯法,分别记录每个可能的答案。
代码如下:

public class Solution {
public List<String> letterCombinations(String digits) {
List<String> list = new ArrayList<String>();
if(digits == null || digits.length() == 0) return list;
String[] str = {"","", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
getLetter(digits, str, 0, "", list);
return list;
}

public void getLetter(String digits, String[] str, int start, String s, List<String> list) {
if(s.length() == digits.length()) {
list.add(s);
}
if(start < digits.length())
for(int i = 0; i < str[digits.charAt(start) - '0'].length(); i++) {
getLetter(digits, str, start + 1, s + str[digits.charAt(start) - '0'].charAt(i), list);
}
}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值