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);
        }
    }

 

posted on 2019-01-25 13:21  无名路人甲  阅读(81)  评论(0编辑  收藏  举报