17. Letter Combinations of a Phone Number
DFS
class Solution {
private static String[] keys = new String[]{"","","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"};
public List<String> letterCombinations(String digits) {
List<String> result = new LinkedList<String>();
findConbinations(result, 0, digits, "");
return result;
}
private void findConbinations(List<String> list, int index, String digits, String str){
if (digits.length() == 0) return;
if(index == digits.length()){
list.add(str);
}else{
String key = keys[digits.charAt(index)-'0'];
for(int i =0; i<key.length(); i++){
// here, str+key.charAt(i) generates a new string object;
findConbinations(list, index+1, digits, str+key.charAt(i));
}
}
}
}
Last updated
Was this helpful?