[LeetCode]Letter Combinations of a Phone Number

48 篇文章 0 订阅

题目

Number: 17
Difficulty: Medium
Tags: Backtracking, String

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键输入字母,给出输入的数字,输出所有可能的字母组合。

类似于笛卡尔积。

代码

非递归:

vector<string> letterCombinations(string digits) {
    vector<string> result;
    if(digits.empty())
        return result;
    string buttons[] = {"0", "1", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
    result.push_back("");
    for(int i = 0; i < digits.size(); ++i)
    {
        vector<string> temp;
        string ch = buttons[digits[i] - '0'];
        for(int j = 0; j < ch.size(); ++j)
            for(int k = 0; k < result.size(); ++k)
                temp.push_back(result[k] + ch[j]);
        result = temp;
    }
    return result;
}

回溯的方法:

/* BackTracking */
vector<string> letterCombinations(string digits){
    vector<string> result;
    if(digits.empty())
        return result;
    string buttons[] = {"0", "1", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};  
    vector<string> temp = letterCombinations(digits.substr(1));
    string ch = buttons[digits[0] - '0'];
    for(int i = 0; i < ch.size(); ++i)
    {
        if(temp.empty())
            result.push_back(string(1, ch[i]));
        else
            for(int j = 0; j < temp.size(); ++j)
                result.push_back(ch[i] + temp[j]);
    }
    return result;
}

总结

char to string:

string s(1, c); 
std::cout << s << std::endl;

and

std::cout << string(1, c) << std::endl;

and

string s; 
s.push_back(c); 
std::cout << s << std::endl;
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值