Skip to content

Instantly share code, notes, and snippets.

@daifu
Created March 16, 2013 02:23
Show Gist options
  • Select an option

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

Select an option

Save daifu/5174647 to your computer and use it in GitHub Desktop.
Given a digit string, return all possible letter combinations that the number could represent.
/*
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 {
public ArrayList<String> letterCombinations(String digits) {
// Start typing your Java solution below
// DO NOT write main() function
char[][] map = {{},{},{'a','b','c'},{'d','e','f'},
{'g','h','i'},{'j','k','l'},{'m','n','o'},
{'p','q','r','s'}, {'t','u','v'}, {'w','x','y','z'}};
ArrayList<String> ret = new ArrayList<String>();
if(digits.length() == 0) {
ret.add("");
return ret;
}
StringBuffer str = new StringBuffer();
combines(0, digits, str, map, ret);
return ret;
}
public void combines(int start, String digits, StringBuffer str, char[][] map, ArrayList<String> ret) {
int curNum = digits.charAt(start) - '0';
for(int i = 0; i < map[curNum].length; i++) {
str.append(map[curNum][i]);
if(start == (digits.length() - 1)) {
ret.add(str.toString());
}
if(start < digits.length() - 1)
combines(start+1, digits, str, map, ret);
// delete the last one
str.deleteCharAt(str.length() - 1);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment