[LeetCode] Letter Combinations of a Phone Number

来源:互联网 发布:软件授权使用说明书 编辑:程序博客网 时间:2024/06/08 17:50

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.

该题的主要意思:给你2-9数字中的任意几个,其中每个数字都包含三个字母,其所包含的字母如上图所示,求出这些数字所构成的所有组合。

该种题型较为简单,我们可以通过深度优先遍历求解。

深度优先遍历算法如下:

复杂度:时间 O(n2)递归栈空间

思路:首先建一个表,来映射号码和字母的关系。然后对号码进行深度优先搜索,对于每一位,从表中找出数字对应的字母,这些字母就是本轮搜索的几种可能。

char str[1000];vector<string>result;class Solution {public:    vector<string> letterCombinations(string digits) {        int len = digits.size();        if (len == 0)            return result;        string nums[] = {" ", " ", "ab", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};        digitsDeal(digits, 0, len, nums);        return result;    }public:    void digitsDeal(string &digits, int i, int len, string *nums)    {        if(i == len)        {            str[len] = '\0';            string temp = str;            result.push_back(temp);            return;        }        int index = digits[i]-'0';        for(int  j= 0; j < nums[index].size(); ++j)        {            str[i] = nums[index][j];            digitsDeal(digits, i+1, len, nums);        }    }};



阅读全文
0 0