Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[LeetCode] 17. Letter Combinations of a Phone Number #17

Open
grandyang opened this issue May 30, 2019 · 1 comment
Open

[LeetCode] 17. Letter Combinations of a Phone Number #17

grandyang opened this issue May 30, 2019 · 1 comment

Comments

@grandyang
Copy link
Owner

grandyang commented May 30, 2019


请点击下方图片观看讲解视频
Click below image to watch YouTube Video
Video

Given a string containing digits from 2-9 inclusive, return all possible letter combinations that the number could represent. Return the answer in any order.

A mapping of digits to letters (just like on the telephone buttons) is given below. Note that 1 does not map to any letters.

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"]

Constraints:

  • 0 <= digits.length <= 4
  • digits[i] is a digit in the range ['2', '9'].

这道题让我们求电话号码的字母组合,即数字2到9中每个数字可以代表若干个字母,然后给一串数字,求出所有可能的组合,相类似的题目有 Path Sum IISubsets IIPermutationsPermutations IICombinationsCombination SumCombination Sum II 等等。这里可以用递归 Recursion 来解,需要建立一个字典,用来保存每个数字所代表的字符串,然后还需要一个变量 pos,记录当前生成的字符串的字符个数,实现套路和上述那些题十分类似。在递归函数中首先判断 pos,如果跟 digits 中数字的个数相等了,将当前的组合加入结果 res 中,然后返回。我们通过 digits 中的数字到 dict 中取出字符串,然后遍历这个取出的字符串,将每个字符都加到当前的组合后面,并调用递归函数即可,参见代码如下:

解法一:

class Solution {
public:
    vector<string> letterCombinations(string digits) {
        if (digits.empty()) return {};
        vector<string> res;
        vector<string> dict{"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
        dfs(digits, dict, 0, "", res);
        return res;
    }
    void dfs(string digits, vector<string>& dict, int pos, string cur, vector<string>& res) {
        if (pos == digits.size()) { res.push_back(cur); return; }
        string str = dict[digits[pos] - '0'];
        for (int i = 0; i < str.size(); ++i) {
            dfs(digits, dict, pos + 1, cur + str[i], res);
        }
    }
}; 

这道题也可以用迭代 Iterative 来解,在遍历 digits 中所有的数字时,先建立一个临时的字符串数组t,然后跟上面解法的操作一样,通过数字到 dict 中取出字符串 str,然后遍历取出字符串中的所有字符,再遍历当前结果 res 中的每一个字符串,将字符加到后面,并加入到临时字符串数组t中。取出的字符串 str 遍历完成后,将临时字符串数组赋值给结果 res,具体实现参见代码如下:

解法二:

class Solution {
public:
    vector<string> letterCombinations(string digits) {
        if (digits.empty()) return {};
        vector<string> res{""};
        vector<string> dict{"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
        for (int i = 0; i < digits.size(); ++i) {
            vector<string> t;
            string str = dict[digits[i] - '0'];
            for (int j = 0; j < str.size(); ++j) {
                for (string s : res) t.push_back(s + str[j]);
            }
            res = t;
        }
        return res;
    }
};

Github 同步地址:

#17

类似题目:

Generate Parentheses

Combination Sum

Binary Watch

参考资料:

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

https://leetcode.com/problems/letter-combinations-of-a-phone-number/discuss/8109/My-recursive-solution-using-Java

https://leetcode.com/problems/letter-combinations-of-a-phone-number/discuss/8097/My-iterative-sollution-very-simple-under-15-lines

https://leetcode.com/problems/letter-combinations-of-a-phone-number/discuss/8207/Concise-15-line-Java-Iterative-Solution-very-Straight-Forward-with-Brief-Explanation

LeetCode All in One 题目讲解汇总(持续更新中...)

(欢迎加入博主的知识星球,博主将及时答疑解惑,并分享刷题经验与总结,快快加入吧~)

知识星球 喜欢请点赞,疼爱请打赏❤️~.~

微信打赏

|

Venmo 打赏


---|---

@lld2006
Copy link

lld2006 commented Jun 29, 2020

解法2 利用res.swap(t);会更好,因为swap只需要交换若干pointer, 而copy vector of string 会慢很多。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants