leetcode 17. Letter Combinations of a Phone Number

来源:互联网 发布:打开软件分辨率低 编辑:程序博客网 时间:2024/06/04 01:34

1.题目

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"].

根据电话上所按的数字,得到可能的字符的组合。

2.思路 

我们可以创建一个字符串数组string letters[8] = {"abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};   代表数字2-9所映射的字符。

要得到所有可能的解,自然的想到用dfs.

<pre name="code" class="cpp">class Solution {public:    vector<string> ret;    string letters[8] = {"abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};    void dfs(int dep,int maxdep,string &s,string ans)    {        if(maxdep==0) return ;        else if(dep == maxdep)        {ret.push_back(ans);return;}        for(int i=0;i<letters[s[dep]-'2'].size();i++)            dfs(dep+1,maxdep,s,ans+letters[s[dep]-'2'][i]);     }    vector<string> letterCombinations(string digits) {        dfs(0, digits.size(), digits,"");        return ret;    }};


0 0
原创粉丝点击