【中等】17-电话号码的字母组合 Letter Combinations of a Phone Number

题目

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.\

给定一个仅包含数字 2-9 的字符串,返回所有它能表示的字母组合。

给出数字到字母的映射如下(与电话按键相同)。注意 1 不对应任何字母。

Example:

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

来源:力扣(Leetcode)
链接:https://leetcode-cn.com/problems/letter-combinations-of-a-phone-number/

解法

方法一:广度优先搜索

解题思路

当digits为2时,结果应为["a""b""c"],当digit增加一位变成23时,实际上是对2的结果的每一位后面都分别增添数字3上的"def",由此得出算法,对于每一位数字,依次向其前方的digit子串得到的结果补充该数字上的字符即可

代码

class Solution {
public:
    vector<string> letterCombinations(string digits) {
        string phone[8] = {"abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
        vector<string> res;
        if(digits.size() == 0) return res;
        res.push_back("");
        for(int s = 0; s < digits.size(); ++s){
            int n = digits[s]-'0';
            if(n == 1){
                res.clear();
                return res;
            }
            string curr = phone[n-2];
            int curr_num = res.size();
            for(int i=0; i < curr_num; ++i){
                for(int j=0; j < curr.size(); ++j){
                    res.push_back(res[0]+curr.substr(j, 1));
                }
                res.erase(res.begin());
            }
        }
        return res;
    }
};

方法二:回溯算法/深度优先算法

解题思路

第一种方法是每次考虑最终字符串的每一个位置可能放置什么字符,然后进行组合,回溯算法就是深度优先找到一个可能的解,再依次回头检查哪一位的字符可能被修改,修改后再向后寻找

代码

class Solution {
public:
    string phone[8] = {"abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
    vector<string> res;
    bool wrong = false;
    void get_str(string curr, string digits){
        int pos = curr.size();
        if(pos >= digits.size()) res.push_back(curr);
        else{
            int p = digits[pos]-'0';
            if(p==1) {wrong = true; return;}
            string phone_list = phone[p-2];
            for(int i=0; i < phone_list.size(); ++i){
                get_str(curr+phone_list.substr(i, 1), digits);
            }
        }
    }
    vector<string> letterCombinations(string digits) {
        if(digits.size() == 0) return res;
        get_str("", digits);
        if(wrong) res.clear();
        return res;
    }
};
posted @ 2020-04-23 17:28  陌良  阅读(159)  评论(0编辑  收藏  举报