[LeetCode] 17. Letter Combinations of a Phone Number ☆☆

时间:2023-02-05 06:04:14

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.

[LeetCode] 17. Letter Combinations of a Phone Number ☆☆

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.

解法1:

  采用队列的方法,遍历digits的每一位数字,对于遍历到的数字,将队列中所有的字符串从头部移除,加上当前数字对应的字母后依次添加到队列后端。

public class Solution {
public List<String> letterCombinations(String digits) {
List<String> res = new ArrayList<>(); if (digits == null || digits.length() == 0) {
return res;
} String[] letters = new String[]{"abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
res.add(""); for (int i = 0; i < digits.length(); i++) {
int size = res.size();
String str = letters[digits.charAt(i) - '2'];
for (int j = 0; j < size; j++) {
String front = res.remove(0); // 不是remove(j),每次都应该移除第一个字符串
for (int k = 0; k < str.length(); k++) {
res.add(front + str.charAt(k));
}
}
}
return res;
}
}

解法2:

  采用递归的方法,每次添加一个字母后进行下一次递归:

public class Solution {
public List<String> letterCombinations(String digits) {
List<String> res = new ArrayList<>(); if (digits == null || digits.length() == 0) {
return res;
} String[] letters = new String[]{"abc", "def", "ghi", "jkl", "mno", "pqrs", "utv", "wxyz"};
helper(res, letters, digits, "");
return res;
} public void helper(List<String> res, String[] letters, String digits, String temp) {
if (digits.length() == 0) {
res.add(temp);
return;
}
String str = letters[digits.charAt(0) - '2'];
for (int i = 0; i < str.length(); i++) {
helper(res, letters, digits.substring(1), temp + str.charAt(i));
}
}
}

解法2: