Solution
其实就是笛卡尔积
image.pngclass Solution {
public List<String> letterCombinations(String digits) {
List<String> result = new ArrayList<> ();
if (digits == null || digits.length () == 0) {
return result;
}
Map<String, String> phoneDigits = new HashMap<> ();
phoneDigits.put ("0", "");
phoneDigits.put ("1", "");
phoneDigits.put ("2", "abc");
phoneDigits.put ("3", "def");
phoneDigits.put ("4", "ghi");
phoneDigits.put ("5", "jkl");
phoneDigits.put ("6", "mno");
phoneDigits.put ("7", "pqrs");
phoneDigits.put ("8", "tuv");
phoneDigits.put ("9", "wxyz");
letterCombinationsHelper (digits, phoneDigits, 0, "", result); // currentIndex, combinationEntry
return result;
}
private void letterCombinationsHelper (String digits,
Map<String, String> phoneDigits,
int currentIndex,
String combinationEntry,
List<String> result) {
if (currentIndex == digits.length ()) {
result.add (combinationEntry);
return;
}
String currentLetters = phoneDigits.get (digits.substring (currentIndex, currentIndex + 1));
for (int i = 0; i < currentLetters.length (); i ++) {
combinationEntry = combinationEntry + currentLetters.substring (i, i + 1);
letterCombinationsHelper (digits, phoneDigits, currentIndex + 1, combinationEntry, result);
combinationEntry = combinationEntry.substring (0, combinationEntry.length () - 1);
}
}
}
网友评论