017 Letter Combinations of a Phone Number[M]

1 题目描述

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.

《017 Letter Combinations of a Phone Number[M]》
其实就是九键键盘

Note:

Although the above answer is in lexicographical order, your answer could be in any order you want.

难度:Medium

2 题目样例

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

3 题意分析

求排列组合即可。

4 思路分析

迭代的话其实也就是递归展开版,所以直接写成递归算了。

代码如下

class Solution {
public:
    vector<string> letterCombinations(string digits) {
        int len = digits.size();
        vector<string> ans;
        vector<string> s = {"", // for 1-indexed                             "", "abc", "def", 
                            "ghi" , "jkl", "nmo", 
                            "pqrs", "tuv", "wxyz"};
        function<void(string, int)> f;
        f = [&f, &s, len, &digits, &ans](string bf, int i){
            if(i==len){
                if(bf.size()!=0)
                    ans.emplace_back(bf);
            }
            else
                for(auto &c:s[digits[i]-'0'])
                    f(bf+c, i+1);
        };
        f(string(""), 0);
        return ans;
    }
};

整体时间复杂度 《017 Letter Combinations of a Phone Number[M]》 但是 《017 Letter Combinations of a Phone Number[M]》 ,同时空间复杂度也是 《017 Letter Combinations of a Phone Number[M]》《017 Letter Combinations of a Phone Number[M]》 ,其中n是digits的长度,复杂度用递归树法很容易看出。

5 后记

果然lambda和std::function满天飞就是很爽,不过还是要多学习一个写法啊。

    原文作者:澪同学
    原文地址: https://zhuanlan.zhihu.com/p/33773657
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞