[LintCode] Letter Combinations of a Phone Number 电话号码的字母组合

本文介绍了解决电话号码字母组合问题的两种方法。方法一使用递归进行深度优先搜索,方法二采用迭代方式实现。通过这两种不同的算法思路,可以有效地生成所有可能的字母组合。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 

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.

Cellphone

 Notice

Although the above answer is in lexicographical order, your answer could be in any order you want.

Example

Given "23"

Return["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"]

 

LeetCode上的原题,请参见我之前的博客Letter Combinations of a Phone Number

 

解法一:

class Solution {
public:
    /**
     * @param digits A digital string
     * @return all posible letter combinations
     */
    vector<string> letterCombinations(string& digits) {
        if (digits.empty()) return {};
        vector<string> res;
        vector<string> v{"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
        helper(digits, v, 0, "", res);
        return res;
    }
    void helper(string& digits, vector<string>& v, int level, string out, vector<string>& res) {
        if (level == digits.size()) {
            res.push_back(out);
            return;
        }
        string t = v[digits[level] - '0'];
        for (int i = 0; i < t.size(); ++i) {
            out.push_back(t[i]);
            helper(digits, v, level + 1, out, res);
            out.pop_back();
        }
    }
};

 

解法二:

class Solution {
public:
    /**
     * @param digits A digital string
     * @return all posible letter combinations
     */
    vector<string> letterCombinations(string& digits) {
        if (digits.empty()) return {};
        vector<string> res{""};
        vector<string> v{"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
        for (int i = 0; i < digits.size(); ++i) {
            string str = v[digits[i] - '0'];
            int n = res.size();
            for (int j = 0; j < n; ++j) {
                string t = res.front();
                res.erase(res.begin());
                for (int k = 0; k < str.size(); ++k) {
                    res.push_back(t + str[k]);
                }
            }
        }
        return res;
    }
};

 

转载于:https://www.cnblogs.com/grandyang/p/5690104.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值