Leetcode之letter Combinations Of A Phone Number 字符组合
26 June 2014
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.
Input:Digit string "23" Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].
解法:字符组合问题,一般用递归都能很快解决。
代码如下:
//{java}
public class Solution {
public List<String> letterCombinations(String digits) {
String []table = new String []{""," ","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"};
List<String> ls= new ArrayList<String>();
if(digits.length()==0)
{
ls.add("");
return ls;
}
char c = digits.charAt(0);
for(int i=0;i<table[c-48].length();i++)
{
char t = table[c-48].charAt(i);
for(String temp:letterCombinations(digits.substring(1,digits.length())))
{
ls.add(t+temp);
}
}
return ls;
}
}
blog comments powered by Disqus