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.

Example:

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

思路:index不用for循环,直接在内部+1就行了


currentString + chars[i]这种写法比sb.append更加简洁一些


退出的条件是由index+1得出来的
if (index == digits.length())

 

也不知道为啥dfs函数一定要返回什么东西……

 


class Solution {
    private final String[] keys = {"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
    
    public List<String> letterCombinations(String digits) {
        //cc
        List<String> results = new ArrayList<String>();
        if (digits == null || digits.length() == 0)
            return results;
        
        //dfs
        dfs(digits, 0, "", results);
        
        //return 
        return results;
    }
    
    public List<String> dfs(String digits, 
                            int index, String currentString,
                            List<String> results) {
        //exit
        if (index == digits.length()) {
            results.add(currentString);
            return results;
        }
        
        //for loop
        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

 



posted @ 2020-09-01 08:33  苗妙苗  阅读(117)  评论(0编辑  收藏  举报