当前位置:网站首页>Leetcode: 17. letter combination of phone number

Leetcode: 17. letter combination of phone number

2022-07-23 14:56:00 uncle_ ll

17. Letter combination of telephone number

source : Power button (LeetCode)

link : https://leetcode.cn/problems/letter-combinations-of-a-phone-number/

Given a number only 2-9 String , Returns all the letter combinations it can represent . You can press In any order return .

The mapping of numbers to letters is given as follows ( Same as phone key ). Be careful 1 Does not correspond to any letter .

 Insert picture description here

Example 1:

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

Example 2:

 Input :digits = ""
 Output :[]

Example 3:

 Input :digits = "2"
 Output :["a","b","c"]

Tips :

0 <= digits.length <= 4
digits[i]  Is the scope of  ['2', '9']  A number of .

solution

  • recursive : If digits The length of is equal to 1, Map to string and convert to list ; If the length is greater than 1 Words , Recursion first n-1 The result of length , The last number is mapped ; Write a double loop to combine .
  • to flash back : First, build a hash table to represent the phone number disk , Then based on digits Go back , The string is initially empty . Take one digit of the phone number at a time , Get all possible letters corresponding to the number from the hash table , And insert one of the letters after the existing alphabet , Then continue to process the last digit of the phone number , Until all the numbers in the phone number are processed , That is to get a complete alphabetic arrangement . And then go back , Traverse the rest of the alphabet .

Code implementation

recursive

python Realization

class Solution:
    def letterCombinations(self, digits: str) -> List[str]:
        if not digits or len(digits) == 0:
            return []
        
        mapping = {
    '2': 'abc', '3': 'def', '4': 'ghi', '5': 'jkl', 
                   '6': 'mno', '7': 'pqrs', '8': 'tuv', '9': 'wxyz'}

        if len(digits) == 1:
            return list(mapping[digits[0]])
        
        prev_letters = self.letterCombinations(digits[:-1])
        reverse_letter = mapping[digits[-1]]
        return [s + c for s in prev_letters for c in reverse_letter]

c++ Realization

class Solution {
    
public:
    vector<string> letterCombinations(string digits) {
    
        int n = digits.size();
        if (n == 0) return {
    };

        unordered_map<char, string> maps {
    
        {
    '2', "abc"},
        {
    '3', "def"},
        {
    '4', "ghi"},
        {
    '5', "jkl"},
        {
    '6', "mno"},
        {
    '7', "pqrs"},
        {
    '8', "tuv"},
        {
    '9', "wxyz"}
    };

        vector<string> res;

        if (n == 1) {
    
            string letter = maps[digits[0]];
            for (char ch: letter) {
    
                string s;
                res.push_back(s+ch);
            }
            return res;
        }
        string digits2 = digits.substr(0, n-1);

        vector<string> prev_letters = letterCombinations(digits2);
        string letter = maps[digits[n-1]];
        for (auto prev_letter: prev_letters) {
    
            for (char ch: letter) {
    
                res.push_back(prev_letter+ch);
            }       
        }
        return res;
    }
};

Complexity analysis

  • Time complexity : O ( 3 m + 4 n ) O(3^m+4^n) O(3m+4n) m It's corresponding to 3 Alphanumeric number ,n It's corresponding to 4 The number of alphanumeric , There are different combinations of letters 3 m × 4 n 3^m \times 4^n 3m×4n Kind of , You need to traverse every letter combination .
  • Spatial complexity : O ( m + n ) O(m+n) O(m+n)

to flash back

python Realization

class Solution:
    def letterCombinations(self, digits: str) -> List[str]:
        if not digits or len(digits) == 0:
            return []
        
        letters = {
    
            '2': 'abc',
            '3': 'def',
            '4': 'ghi',
            '5': 'jkl',
            '6': 'mno',
            '7': 'pqrs',
            '8': 'tuv',
            '9': 'wxyz'
        }

        res = []

        n = len(digits)

        def helper(path, depth):
            if depth == n:
                res.append(''.join(path))
                return
            
            string = letters[digits[depth]]
            for ch in string:
                path.append(ch)
                helper(path, depth+1)
                path.pop()
        helper([], 0)
        return res

c++ Realization

class Solution {
    
    vector<string> res;

    unordered_map<char, string> maps {
    
        {
    '2', "abc"},
        {
    '3', "def"},
        {
    '4', "ghi"},
        {
    '5', "jkl"},
        {
    '6', "mno"},
        {
    '7', "pqrs"},
        {
    '8', "tuv"},
        {
    '9', "wxyz"}
    };

public:
    void helper(vector<char> path, int depth, string digits,vector<string>& res, unordered_map<char, string> maps) {
    
        if (depth == digits.size()) {
    
            string tmp;
            for (auto ch: path) {
    
                tmp += ch;
            }
            res.push_back(tmp);
            return ;
        }

        string letters = maps[digits[depth]];
        for (int i=0; i<letters.size(); i++) {
    
            char ch = letters[i];
            path.push_back(ch);
            helper(path, depth+1, digits, res, maps);
            path.pop_back();
        }
    }

    vector<string> letterCombinations(string digits) {
    
        if (digits.size() == 0)
            return {
    };

        helper({
    }, 0, digits, res, maps);
        return res;    
    }
};

Complexity analysis

  • Time complexity : O ( 3 m + 4 n ) O(3^m+4^n) O(3m+4n) m It's corresponding to 3 Alphanumeric number ,n It's corresponding to 4 The number of alphanumeric , There are different combinations of letters 3 m × 4 n 3^m \times 4^n 3m×4n Kind of , You need to traverse every letter combination .
  • Spatial complexity : O ( m + n ) O(m+n) O(m+n)

Reference resources

原网站

版权声明
本文为[uncle_ ll]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/204/202207230933401063.html