您的位置:首页 > 其它

LeetCode: Letter Combinations of a Phone Number 解题报告

2014-12-03 20:14 447 查看
[b]Letter Combinations of a Phone Number[/b]

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"].
Note:
Although the above answer is in lexicographical order, your answer could be in any order you want.

public class Solution {
String[] map = {"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};

public List<String> letterCombinations(String digits) {
List<String> ret = new ArrayList<String>();
if (digits == null) {
return ret;
}

dfs(digits, new StringBuilder(), ret, 0);
return ret;
}

public void dfs(String digits, StringBuilder sb, List<String> ret, int index) {
int len = digits.length();
if (index == len) {
ret.add(sb.toString());
return;
}

// get the possiable selections.
String s = map[digits.charAt(index) - '0'];
for (int i = 0; i < s.length(); i++) {
sb.append(s.charAt(i));
dfs(digits, sb, ret, index + 1);
sb.deleteCharAt(sb.length() - 1);
}
}

}


View Code
[b]GITHUB:[/b]

https://github.com/yuzhangcmu/LeetCode_algorithm/blob/master/combination/LetterCombinations.java
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: