LeetCode - 解题笔记 - 17 - Letter Combinations of a Phone Number

Letter Combinations of a Phone Number

Solution 1

就是一个列举所有排列的问题。但是需要额外处理的地方就是输入序列的不定长度,因此无法直接使用循环实现。这里就需要使用典型的递归处理实现,就能够处理任意长度的输入序列了。

  • 时间复杂度: O ( 3 i × 4 N − i ) O(3^i \times 4^{N - i}) O(3i×4Ni),其中 N N N为输入序列的长度, i i i为其中对应三个字母的数字个数
  • 空间复杂度: O ( 3 i × 4 N − i ) O(3^i \times 4^{N - i}) O(3i×4Ni),其中 N N N为输入序列的长度, i i i为其中对应三个字母的数字个数
class Solution {
private:
    vector<string> ans;
    map<char, vector<char>> number2letter = {
            {'2', {'a', 'b', 'c'}},
            {'3', {'d', 'e', 'f'}},
            {'4', {'g', 'h', 'i'}},
            {'5', {'j', 'k', 'l'}},
            {'6', {'m', 'n', 'o'}},
            {'7', {'p', 'q', 'r', 's'}},
            {'8', {'t', 'u', 'v'}},
            {'9', {'w', 'x', 'y', 'z'}}
        };
    
    void getLetters(string digits, int pos, string temp) {
        if (pos == digits.size()) {
            ans.push_back(temp);
            return;
        }
        
        vector<char> letters = number2letter[digits[pos]];
        
        for (auto letter: letters) {
            string tempNew = temp + letter;
            getLetters(digits, pos + 1, tempNew);
        }
    }
    
public:
    vector<string> letterCombinations(string digits) {
        if (digits.size() == 0) {
            return vector<string>();
        }
        
        getLetters(digits, 0, "");
        
        return ans;
    }
};

Solution 2

Solution 1对应的Python实现。

class Solution:
    def letterCombinations(self, digits: str) -> List[str]:
        number2letter = {
            "2": ["a", "b", "c"],
            "3": ["d", "e", "f"],
            "4": ["g", "h", "i"],
            "5": ["j", "k", "l"],
            "6": ["m", "n", "o"],
            "7": ["p", "q", "r", "s"],
            "8": ["t", "u", "v"],
            "9": ["w", "x", "y", "z"]
        }
        
        ans = list()
        
        def getLetters(tempStr:str, currentPos:int) -> None:
            if currentPos >= len(digits):
                ans.append(tempStr)
            else:
                for currentChar in number2letter[digits[currentPos]]:
                    tempStrNew = tempStr +  currentChar
                    getLetters(tempStrNew, currentPos + 1)
                    
        if len(digits) == 0:
            return ans
        else:
            getLetters("", 0)
            return ans
                
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值