Letter Combinations of a Phone Number
public class Solution {
/**
* @param digits: A digital string
* @return: all posible letter combinations
*/
public List<String> letterCombinations(String digits) {
// write your code here
/*for (int i = 'a'; i <= 'c'; i++) {
for (int j = 'j'; j <= 'l'; j++) {
for (int k = 'd'; k <= 'f'; k++) {
print();
}
}
}*/
String[] phone = {"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
List<String> ans = new ArrayList<>();
if (digits == null || digits.length() == 0) {
return ans;
}
dfs(0, "", digits, phone, ans);
return ans;
}
private void dfs(int x, String str, String digits, String[] phone, List<String> ans) {
if (x == digits.length()) {
ans.add(str);
return;
}
int d = digits.charAt(x) - '0';
for (char c : phone[d].toCharArray()) {
dfs(x + 1, str + c, digits, phone, ans);
}
}
}
最后更新于
这有帮助吗?