17. Letter Combinations of a Phone Number

来源:互联网 发布:天天卡牌淘宝杂货铺 编辑:程序博客网 时间:2024/05/29 09:21

题目:Letter Combinations of a Phone Number

原题链接:https://leetcode.com/problems/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”].

给出一个数字串,返回在9宫格键盘上所有可能的字母组合。
如图,按下23,则有可能出现的组合有[“ad”, “ae”, “af”, “bd”, “be”, “bf”, “cd”, “ce”, “cf”].

看这个电话键盘可以发现,除了2到9之外的按键都是没有字母的,所以第一步我们可以把其他多余的字符都剔除掉,假设得到的字符串为temp。
然后采用回溯的方法。
由于temp的长度已知,我们就可以确定结果中字母串的长度,这样可以预先分配好空间,假设我们用字符串 s 来存放临时的结果。
设一个cnt[10000]数组。其中cnt[ i ]表示当前数字temp[ i ]所对应的字母的下标。一旦下标到达上限,我们就把下标置0,并且让i - 1,回到上一个数字重新开始选择。
当i == temp.length()时,就是一个可能的结果,存起来。
当回溯到 i == -1时,回溯结束。

代码如下:

class Solution {public:    vector<string> letterCombinations(string digits) {        vector<string> ans;        string num[10] = {"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};        string temp, ret;        int len = digits.length();        for(int i = 0; i < len; ++i) {            if(digits[i] >= '2' && digits[i] <= '9') temp += digits[i];        }        len = temp.length();        if(len == 0) return ans;        int cnt[10000] = {0};        int i = 0, j = 0;        string s;        s.resize(len);        while(i >= 0) {            if(i == len) {                ans.push_back(s);                i--;            }else if(cnt[i] == num[temp[i] - '0'].length()){                cnt[i] = 0;                i--;            }else{                s[i] = num[temp[i] - '0'][cnt[i]];                cnt[i]++;                i++;            }        }        return ans;    }};
0 0
原创粉丝点击