[leetcode] 17. Letter Combinations of a Phone Number 解题报告

题目链接:https://leetcode.com/problems/letter-combinations-of-a-phone-number/

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.


思路:建一张表,简单的深搜。每次取那个数字的字母表的一个值。

代码如下:

class Solution {
public:
    void DFS(const string& digits, string tem, int index)
    {
        if(tem.size() == digits.size())
        {
            result.push_back(tem);
            return;
        }
        if(digits[index] < '2' || digits[index] > '9')
            return;
        for(int i = 0; i < table[digits[index]].size(); i++)
            DFS(digits, tem +table[digits[index]][i], index + 1);
    }
    
    vector<string> letterCombinations(string digits) {
        if(digits.size() == 0)
            return result;
        initTable();
        string tem;
        DFS(digits, tem, 0);
        return result;
    }
    
    void initTable()
    {
        table['2'] = "abc";
        table['3'] = "def";
        table['4'] = "ghi";
        table['5'] = "jkl";
        table['6'] = "mno";
        table['7'] = "pqrs";
        table['8'] = "tuv";
        table['9'] = "wxyz";
    }
private:
    map<char, string> table;
    vector<string> result;
};


你可能感兴趣的:(LeetCode,算法,DFS,backtracking,深搜)