您的位置:首页 > 其它

Letter Combinations of a Phone Number

2015-06-16 09:23 337 查看
public class Solution {
public List<String> letterCombinations(String digits) {
List<String> result = new ArrayList<String>();
if (digits == null || digits.length() == 0) {
return result;
}
Map<Character, char[]> map = new HashMap<Character, char[]>();
map.put('0', new char[] {});
map.put('1', new char[] {});
map.put('2', new char[] { 'a', 'b', 'c' });
map.put('3', new char[] { 'd', 'e', 'f' });
map.put('4', new char[] { 'g', 'h', 'i' });
map.put('5', new char[] { 'j', 'k', 'l' });
map.put('6', new char[] { 'm', 'n', 'o' });
map.put('7', new char[] { 'p', 'q', 'r', 's' });
map.put('8', new char[] { 't', 'u', 'v'});
map.put('9', new char[] { 'w', 'x', 'y', 'z' });
StringBuilder sb = new StringBuilder();
myLetterCombinations(result, sb, digits, map);
return result;
}
private void myLetterCombinations(List<String> result, StringBuilder sb, String digits,
Map<Character, char[]> map) {
if (sb.length() == digits.length()) {
result.add(sb.toString());
return;
}
for (char ch : map.get(digits.charAt(sb.length()))) {
sb.append(ch);
myLetterCombinations(result, sb, digits, map);
sb.deleteCharAt(sb.length() - 1);
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Backtracking String