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.
Solution
public class Solution {
public ArrayList<String> letterCombinations(String digits) {
String[] combinations = {"","","abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
ArrayList<String> result = new ArrayList<String>();
String[] resultDigits = new String[digits.length()];
for(int i = 0; i < resultDigits.length; i ++)
resultDigits[i] = combinations[digits.charAt(i) - '0'];
StringBuilder sb = new StringBuilder();
getCombination(resultDigits, result, 0, sb);
return result;
}
public void getCombination(String[] all, ArrayList<String> container, int step, StringBuilder re){
int size = all.length;
if(step == size){
container.add(re.toString());
return;
}
String cur = all[step];
for(int i = 0; i < cur.length(); i ++){
re.append(cur.charAt(i));
getCombination(all, container, step + 1, re);
re.deleteCharAt(re.length() - 1);
}
}
}