[LeetCode]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.

思考:DFS。

class Solution {

public:

    void DFS(vector<string> &res,string ans,int dep,string digits,string dict[])

    {

        if(dep==digits.size())

        {

            res.push_back(ans);

            return;

        }

        for(int i=0;i<dict[digits[dep]-'0'].size();i++)

        {

            DFS(res,ans+dict[digits[dep]-'0'][i],dep+1,digits,dict);

        }

    }

    vector<string> letterCombinations(string digits) {

        vector<string> res;

        string ans="";

        string dict[]={"","","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"};

        DFS(res,ans,0,digits,dict);

        return res;

    }

};

  

你可能感兴趣的:(LeetCode)