LeetCode-17-Letter Combinations of a Phone Number

Posted 无名路人甲

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode-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.

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.

解题思路:

对于输出所有可能的组合这一类型题目,第一时间就应该想到采用回溯法。其中重点就是确定回溯的对象,本题中回溯的对象就是往结果中存的字符串。因为要考虑所有状况,所以处理完之后要还原回来。

    vector<string> letterCombinations(string digits) {
        vector<string> results;
        if(digits.size()<=0) return results;
        string dict[] = {"", "", "abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"};
        Combination(digits,0,results,dict, "");
        return results;
    }
    
    void Combination(string digits, int level, vector<string>& results, string dict[], string curr){
        if(level==digits.size()){
            results.push_back(curr);
            return;
        }
        int index = digits[level] - 0;
        string tmp = dict[index];
        for(int i=0; i < tmp.size(); i++){
            string next = curr + tmp[i];
            Combination(digits, level+1, results, dict, next);
        }
    }

 

以上是关于LeetCode-17-Letter Combinations of a Phone Number的主要内容,如果未能解决你的问题,请参考以下文章

Leetcode 17.——Letter Combinations of a Phone Number

LeetCode-17-Letter Combinations of a Phone Number

LeetCode17. Letter Combinations of a Phone Number

LeetCode17:Letter Combinations of a Phone Number

[LeetCode] 17. Letter Combinations of a Phone Number

Leetcode17Letter Combinations of a Phone Number