码迷,mamicode.com
首页 > 其他好文 > 详细

[LeetCode] Letter Combinations of a Phone Number 电话号码的字母组合

时间:2015-04-24 01:04:53      阅读:138      评论:0      收藏:0      [点我收藏+]

标签:

 

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.

技术分享

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

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

 

这道题让我们求电话号码的字母组合,即数字2到9中每个数字可以代表若干个字母,然后给一串数字,求出所有可能的组合,相类似的题目有 Path Sum II 二叉树路径之和之二Subsets II 子集合之二Permutations 全排列Permutations II 全排列之二Combinations 组合项 Combination Sum 组合之和 Combination Sum II 组合之和之二等等。我们用递归Recursion来解,我们需要建立一个字典,用来保存每个数字所代表的字符串,然后我们还需要一个变量level,记录当前生成的字符串的字符个数,实现套路和上述那些题十分类似,代码如下:

解法一

// Recursion
class Solution {
public:
    vector<string> letterCombinations(string digits) {
        vector<string> res;
        if (digits.empty()) return res;
        string dict[] = {"abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
        letterCombinationsDFS(digits, dict, 0, "", res);
        return res;
    }
    void letterCombinationsDFS(string digits, string dict[], int level, string out, vector<string> &res) {
        if (level == digits.size()) res.push_back(out);
        else {
            string str = dict[digits[level] - 2];
            for (int i = 0; i < str.size(); ++i) {
                out.push_back(str[i]);
                letterCombinationsDFS(digits, dict, level + 1, out, res);
                out.pop_back();
            }
        }
    }
};

 

这道题我们也可以用迭代Iterative来解,具体实现参见代码如下:

解法二

// Iterative
class Solution {
public:
    vector<string> letterCombinations(string digits) {
        vector<string> res;
        if (digits.empty()) return res;
        string dict[] = {"abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
        res.push_back("");
        for (int i = 0; i < digits.size(); ++i) {
            int n = res.size();
            string str = dict[digits[i] - 2];
            for (int j = 0; j < n; ++j) {
                string tmp = res.front();
                res.erase(res.begin());
                for (int k = 0; k < str.size(); ++k) {
                    res.push_back(tmp + str[k]);
                }
            }
        }
        return res;
    }
};

 

[LeetCode] Letter Combinations of a Phone Number 电话号码的字母组合

标签:

原文地址:http://www.cnblogs.com/grandyang/p/4452220.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!