标签:返回 商业 src problems ++ vat hashmap i++ map
给定一个仅包含数字 2-9 的字符串,返回所有它能表示的字母组合。
给出数字到字母的映射如下(与电话按键相同)。注意 1 不对应任何字母。
示例:
输入:"23"
输出:["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].
说明:
尽管上面的答案是按字典序排列的,但是你可以任意选择答案输出的顺序。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/letter-combinations-of-a-phone-number
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
1 public class Solution { 2 private Map<Integer, char[]> map = null; 3 private char[] digits = null; 4 5 private List<String> helper(int cur){ 6 List<String> res = new ArrayList<>(); 7 if (cur == 0) { 8 char[] value = map.get(digits[cur]-‘0‘); 9 for (char c : value) { 10 res.add(c+""); 11 } 12 return res; 13 } 14 List<String> sub = helper(cur - 1); 15 16 char[] value = map.get(digits[cur]-‘0‘); 17 for (String s : sub) { 18 for (char c : value) { 19 res.add(s+c); 20 } 21 } 22 return res; 23 } 24 25 public List<String> letterCombinations(String digits) { 26 if (digits.equals("")) return new ArrayList<>(); 27 int count, digit = 2; 28 29 map = new HashMap<>(); 30 this.digits = digits.toCharArray(); 31 32 for (char i = ‘a‘; i <= ‘z‘;) { 33 count = (digit == 7 || digit == 9) ? 4 :3; 34 char[] value = new char[count]; 35 for (int j = 0; j < count; j++) { 36 value[j] = i++; 37 } 38 map.put(digit++, value); 39 } 40 return helper(digits.length()-1); 41 } 42 43 public static void main(String[] args) { 44 List<String> list = new Solution().letterCombinations(""); 45 for (String s : list) { 46 System.out.print(s+", "); 47 } 48 } 49 }
标签:返回 商业 src problems ++ vat hashmap i++ map
原文地址:https://www.cnblogs.com/yfs123456/p/11613940.html