Skip to content

Instantly share code, notes, and snippets.

@daifu
Created May 16, 2013 17:00
Show Gist options
  • Select an option

  • Save daifu/5593279 to your computer and use it in GitHub Desktop.

Select an option

Save daifu/5593279 to your computer and use it in GitHub Desktop.
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"].
Note:
Although the above answer is in lexicographical order, your answer could be in any order you want.
Algorithm
1. It needs to be done using recursively with the length of the numbers and the chars for each number.
*/
public class Solution {
public ArrayList<String> letterCombinations(String digits) {
// Start typing your Java solution below
// DO NOT write main() function
ArrayList<String> ret = new ArrayList<String>();
if(digits.length() == 0) {
ret.add("");
return ret;
}
StringBuffer sb = new StringBuffer();
String[] numStrMap = {"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
letterCombinationsHelper(digits, ret, 0, sb, numStrMap);
return ret;
}
public void letterCombinationsHelper(String digits, ArrayList<String> ret, int start, StringBuffer sb, String[] numStrMap) {
if(sb.length() == digits.length()) {
ret.add(sb.toString());
return;
}
for(int i = start; i < digits.length(); i++) {
int index = digits.charAt(i)-'0';
for(int j = 0; j < numStrMap[index].length(); j++) {
sb.append(numStrMap[index].charAt(j));
letterCombinationsHelper(digits, ret, i+1, sb, numStrMap);
sb.deleteCharAt(sb.length() - 1);
}
}
return;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment