[LeetCode] 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.
Telephone-keypad

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.

[中文翻译]
给定一个数字字符串,返回数字可能代表的所有可能的字母组合。
下面给出了数字到字母的映射(就像电话上的按钮)。

输入: 数字字符串“23”
输出: [“ad”, “ae”, “af”, “bd”, “be”, “bf”, “cd”, “ce”, “cf”].

注意:
虽然上面的答案是按字典顺序,你的答案可以是任何你想要的顺序。

[解题思路]
显然可以把映射关系存成一个二维数组,然后写个十重for循环可以解决问题。但这不是一个通用的解法。

我们需要的是一个遍历所有可能的遍历方法。实际上,就是一个计数器,在最后一位不断地加1,如果枚举完了当前位,则当前位置零,进位,进位的时候考虑连续进位的情况。每一次计数,对应一个枚举的可能,实际上这就是按字典序在枚举。这样就能实现遍历所有的可能。

[C++代码]

class Solution {
public:
    vector<string> letterCombinations(string digits) {
        vector<string> phoneNumberString;
        vector<string> res;

        phoneNumberString.push_back("");
        phoneNumberString.push_back("");
        phoneNumberString.push_back("abc");
        phoneNumberString.push_back("def");
        phoneNumberString.push_back("ghi");
        phoneNumberString.push_back("jkl");
        phoneNumberString.push_back("mno");
        phoneNumberString.push_back("pqrs");
        phoneNumberString.push_back("tuv");
        phoneNumberString.push_back("wxyz");

        int* index = new int[digits.size() + 1];

        for (int i = 0; i < digits.size() + 1; i++)
            index[i] = 0;

        if (0 == digits.size())
            index[0] = 1;

        while (index[digits.size()] != 1) {
            string addString = "";
            int i;

            for (i = 0; i < digits.size(); i++)
                addString += phoneNumberString.at(digits.at(i) - '0').at(index[i]);

            res.push_back(addString);

            index[0]++;
            i = 0;
            while (i < digits.size() && index[i] == phoneNumberString.at(digits.at(i) - '0').size()) {
                index[i] = 0;
                i++;
                index[i]++;
            }
        }

        delete(index);

        return res;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值