17. Letter Combinations of a Phone Number -Medium

Question

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 -Medium_第1张图片

给出一个包含数字的字符串,请你根据每个数字对应于手机按钮的字母返回所有的组合

Example

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

Solution

  • 回溯解。首先我们先对应每个数字对应的字母String[] S = {“”, “”, “abc”, “def”, “ghi”, “jkl”, “mno”, “pqrs”, “tuv”, “wxyz”};,这样对于输入的任意1-9的数字i,S[i]就是i所对应的字符。然后我们对每个字母进行遍历,将其添加到组合中,并更新下一个输入的数字进行回溯即可

    public class Solution {
        private String[] S = {"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
        public List letterCombinations(String digits) {
            List res = new ArrayList<>();
            if(digits.equals("")) return res;
            backtracking(digits, 0, res, "");
            return res;
        }
    
        public void backtracking(String digits, int start, List res, String temp){
            if(temp.length() > digits.length()) return;
            if(temp.length() == digits.length()){
                res.add(temp);
                return;
            }
    
            // 获得当前数字对应的字符
            String letters = S[digits.charAt(start) - '0'];
            // 分别添加每个字母
            for(int i = 0; i < letters.length(); i++){
                // 对每个字母,接下来更新下一个数字的索引,进行回溯
                backtracking(digits, start + 1, res, temp + letters.charAt(i));
            }
        }
    }

你可能感兴趣的:(java,leetcode,回溯,LeetCode-动态规划,LeetCode-回溯)