LeetCode


题目:

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.

思路:递归。

package recursion;

import java.util.ArrayList;
import java.util.List;

public class LetterCombinationsOfAPhoneNumber {

public List<String> letterCombinations(String digits) {
String[] map
= { " ", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz" };
List
<String> res = new ArrayList<String>();
if (digits == null || digits.length() == 0) return res;
res.add(
"");
return DFS(map, res, digits, 0);
}

private List<String> DFS(String[] map, List<String> subRes, String digits, int pos) {
if (pos == digits.length()) return subRes;
int index = digits.charAt(pos) - '0';
List
<String> res = new ArrayList<String>();
for (String s : subRes) {
for (int j = 0; j < map[index].length(); ++j) {
res.add(s
+ map[index].charAt(j));
}
}

return DFS(map, res, digits, ++pos);
}

public static void main(String[] args) {
// TODO Auto-generated method stub
LetterCombinationsOfAPhoneNumber l = new LetterCombinationsOfAPhoneNumber();
System.out.println(l.letterCombinations(
"23"));
}

}

 

本站声明
本文转载自:http://www.cnblogs.com/shuaiwhu/p/5048536.html     作者:Letter Combinations of a Phone Number - NULL00     发布日期:2015/12/15     本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系我们删除。


 
© 2014-2017 ITdaan.com 粤ICP备14056181号