17. Letter Combinations of a Phone Number 17.电话号码的字母组合

Given a string containing digits from 2-9 inclusive, 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. Note that 1 does not map to any letters.

17. Letter Combinations of a Phone Number 17.电话号码的字母组合_第1张图片

Example:Input: "23"

Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].


思路:
chars[digits]里的每一个,怎么表示? 外层不用循环?化成了DFS里面的变量!

//大index在里面加,因为其实每个letters都加了index
combination(currentString + letters.charAt(i), digits, index + 1, result);

 

digits.charAt(index) - '0' 直接把字母转换成了数字

 

怎么设计dfs函数:先写主函数,由主函数的需求去设计dfs函数

 

dfs内部第二步写边缘条件,第一步写退出条件

 

class Solution {
    private final String[] keys = {"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
    
    public List letterCombinations(String digits) {
        //cc
        //define
        //dfs,有符合的就加到list里
        List results = new ArrayList<>();
        
        if (digits == null || digits == "") return results;
        
        dfs(digits, 0, "", results);
        
        return results;
    }
    
    public List dfs(String digits, int index, String currentString, 
                    List results) {
        //exit
        if (index == digits.length()) {
            results.add(currentString);
            return results;
        }
        
        char[] chars = keys[digits.charAt(index) - '0'].toCharArray();
        for (int i = 0; i < chars.length; i++) {
            dfs(digits, index + 1, currentString + chars[i], results);
        }
        
        return results;
    }
}
View Code

 

 

你可能感兴趣的:(17. Letter Combinations of a Phone Number 17.电话号码的字母组合)