leetcode17:Letter Combinations of a Phone Number
程序员文章站
2022-06-02 22:16:52
...
思路:采用深度优先遍历来做,需要通过变量记录输入的数字串的位置。
public class LetterCombinationsofaPhoneNumber17 {
public static void main(String[] args) {
String digits = "23";
System.out.println(letterCombinations(digits));
}
public static List<String> letterCombinations(String digits) {
List<String> list = new ArrayList<>();
if (digits == null || digits.length() == 0)
return list;
String[] s = { "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz" };
StringBuilder sb = new StringBuilder();
dfs(digits, 0, s, sb, list);
return list;
}
public static void dfs(String digits, int digitIdx, String[] s, StringBuilder sb, List<String> list) {
if (digits.length() == sb.length()) {
list.add(new String(sb.toString()));
return;
}
//注意此处下标的位置
String str = s[digits.charAt(digitIdx)-'2'];
for (int i = 0; i < str.length(); i++) {
sb.append(str.charAt(i));
dfs(digits, digitIdx + 1, s, sb, list);
sb.deleteCharAt(sb.length() - 1);
}
}
}
输出:[ad, ae, af, bd, be, bf, cd, ce, cf]
推荐阅读
-
Leetcode 17. Letter Combinations of a Phone Number(python)
-
LeetCode 17. Letter Combinations of a Phone Number
-
Letter Combinations of a Phone Number(C++)
-
leetcode17:Letter Combinations of a Phone Number
-
LeetCode 17. 电话号码的字母组合 Letter Combinations of a Phone Number
-
leetcode--17. Letter Combinations of a Phone Number
-
LeetCode 17. Letter Combinations of a Phone Number
-
17. Letter Combinations of a Phone Number (Python) dfs(递归 recursion) + 迭代(iterative)
-
Letter Combinations of a Phone Number(C++)