LeetCode_Medium_17. Letter Combinations of a Phone Number

2019.1.28

Given a string containing digits from 2-9 inclusive, 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. Note that 1 does not map to any letters.

Example:

Input: "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.

这道题是按照老式手机九键键盘的数字与字母的对应规则,求出一组全是数字的字符串的对应的字母的全部排列组合。

解法一:递归+字典

我们首先建立一个字典,用来存放数字与字符串的对应关系,在递归过程中,我们设置一个depth记录当前已经扫描到第几个数字了,若depth已经是给定的个数了,那就将当前的组合加入结果res中,再直接return,若不是,则将该数字对应的字符串从字典中取出来,再循环遍历该字符串,将字符串中的字符依次添加到当组合的后面,再递归。

当然,LeetCode的测试用例基本都有空,注意一下特殊情况即可。

C++代码:

class Solution {
public:
    vector<string> letterCombinations(string digits) {
        if (digits.size()==0) return {};
        vector<string> 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 depth, string out, vector<string> &res) {
        if (depth == digits.size()) {res.push_back(out); return;}
        string str = dict[digits[depth] - '0'];
        for (int i = 0; i < str.size(); ++i) {
            letterCombinationsDFS(digits, dict, depth + 1, out + str[i], res);
        }
    }
};

 

解法二:迭代

我们建立一个临时的字符串数组temp,在遍历digits时,每次从dict中取出字符串str,然后遍历取出字符串中的所有字符,再遍历当前结果res中的每一个字符串,将字符加到后面,并加入到临时字符串数组temp中。取出的字符串str遍历完成后,将临时字符串数组赋值给结果res

C++代码:

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

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值