17. Letter Combinations of a Phone Number

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.


17. Letter Combinations of a Phone Number_第1张图片

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

1刷
方法1:DFS + Backtracking:

Time Complexity - O(3n), Space Complexity - O(n)。

方法2: BFS

方法1:

public class Solution {
    public List letterCombinations(String digits) {
        String [] map = {"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
        StringBuilder sb = new StringBuilder();
        List res = new ArrayList<>();
        if(digits == null || digits.length() == 0) return res;
        getLetterCombinations(res, sb, map, digits, 0);
        return res;
    }
    
     private void getLetterCombinations(List res, StringBuilder sb, String[] map, String digits, int pos) {
         if(pos == digits.length()){
             res.add(sb.toString());
             return;
         }
         int index = digits.charAt(pos) - '0';
         String letters = map[index];
         for(int i=0; i

二刷
DFS

public class Solution {
    public List letterCombinations(String digits) {
        List res = new ArrayList<>();
        if(digits == null || digits.length() == 0) return res;
        String [] map = {"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
        StringBuilder sb = new StringBuilder();
        dfs(0, digits, map, res, sb);
        return res;
    }
    
    public void dfs(int index, String digits, String [] map, List res, StringBuilder sb){
        if(sb.length() == digits.length()){
            res.add(sb.toString());
            return;
        }
        
        int num = digits.charAt(index) - '0';
        String cur = map[num];
        for(int i=0; i

你可能感兴趣的:(17. Letter Combinations of a Phone Number)