Letter Combinations of a Phone Number

来源:互联网 发布:20岁的眼泪 知乎 编辑:程序博客网 时间:2024/06/05 18:32

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:    //回溯法    void DFS(string digits, int n, int curIndex, string curStr, unordered_map<char, string> &cmap, vector<string> &ans)    {        if(curIndex > n)            return;        if(curIndex == n)        {            ans.push_back(curStr);            return;        }                int tmpLen = cmap[digits[curIndex]].size();        for(int i = 0; i< tmpLen; ++i)        {            curStr.push_back(cmap[digits[curIndex]][i]);            DFS(digits, n, curIndex + 1, curStr, cmap, ans);            curStr.pop_back();        }    }        vector<string> letterCombinations(string digits) {        int len = digits.size();        vector<string> ans;        if(len >= 1)        {            unordered_map<char, string> cmap;            cmap['2'] = "abc";            cmap['3'] = "def";            cmap['4'] = "ghi";            cmap['5'] = "jkl";            cmap['6'] = "mno";            cmap['7'] = "pqrs";            cmap['8'] = "tuv";            cmap['9'] = "wxyz";            string curStr = "";            DFS(digits, len, 0, curStr, cmap, ans);        }                return ans;    }};


0 0
原创粉丝点击