17.Letter Combinations of a Phone Number(Map; DFS)

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"].
class Solution {

public:

    vector<string> letterCombinations(string digits) {

        m.clear();

        m.insert(make_pair('2',"abc"));

        m.insert(make_pair('3',"def"));

        m.insert(make_pair('4',"ghi"));

        m.insert(make_pair('5',"jkl"));

        m.insert(make_pair('6',"mno"));

        m.insert(make_pair('7',"pqrs"));

        m.insert(make_pair('8',"tuv"));

        m.insert(make_pair('9',"wxyz"));

        

        int len = digits.length();

        dfs("", digits,0);

        return result;

    }

    void dfs(string s, string& digits, int depth){

        char c = digits[depth];

        

        for(int i = 0; i < m[c].length(); i++){

            if(depth==digits.length()-1) {

                result.push_back(s+m[c][i]);

            }

            else dfs(s+m[c][i], digits, depth+1);

        }

    }

private:

    map<char, string> m;

    vector<string> result;

};

 

你可能感兴趣的:(number)