Letter Combinations of a Phone Number

来源:互联网 发布:mac上的视频编辑软件 编辑:程序博客网 时间:2024/06/07 05:49
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.

(1)先说一下遍历的方法。从第一个数字开始,将所有的字母添加到result中,然后,去掉第一个字符串,与下一个数字代表的字母依次组合,并添加到result中,直到完成所有字母的添加。代码如下:

class Solution {public:    vector<string> letterCombinations(string digits) {        vector<string> dv(10); //0~9        dv[2] = "abc";        dv[3] = "def";        dv[4] = "ghi";        dv[5] = "jkl";        dv[6] = "mno";        dv[7] = "pqrs";        dv[8] = "tuv";        dv[9] = "wxyz";        vector<string> result;        if(digits=="")  //数组为空,直接返回            return result;        result.push_back("");  //为首次循环添加一个空字符        for(int i=0;i<digits.size();i++){            int s=result.size();  //不能直接用size()函数,因为result的大小是变化的            for(int j=0;j<s;j++){                string t=result[0];                result.erase(result.begin()); //删除首字母                for(int k=0;k<dv[digits[i]-'0'].size();k++){                    result.push_back(t+dv[digits[i]-'0'][k]);                }            }        }    }};

(2)采用深度优先搜索的办法(DFS),以递归的方式进行遍历。

class Solution {public:      void dfs(string digits, int depth, string path, vector<string> dv, vector<string> &result) {        if(depth == digits.size()) {            result.push_back(path);            return;        }        for(auto c: dv[digits[depth] - '0']) {            dfs(digits, depth+1, path+c, dv, result);        }    }    vector<string> letterCombinations(string digits) {        vector<string> dv(10); //0~9        dv[2] = "abc";        dv[3] = "def";        dv[4] = "ghi";        dv[5] = "jkl";        dv[6] = "mno";        dv[7] = "pqrs";        dv[8] = "tuv";        dv[9] = "wxyz";        vector<string> result;        if(digits.size() == 0) return result;        dfs(digits, 0, "", dv, result);        return result;    }};
0 0