LeetCode OJ-17.Letter Combinations of a Phone Number(DFS)

LeetCode OJ-17.Letter Combinations of a Phone Number(DFS解法)

题目描述

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.

img

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每一个都有其相应的一组英文字母,题目要求从给定的输入数字串中,求解所有可能得到的字母组合情况。每一种字母组合情况的长度都与给定数字串长度相等,因此该条件则可以作为递归的结束条件,可以直接使用DFS解决,这里不会超时。思路类似全排列的求解,具体代码如下:

Code

void dfs(const string &digits, string &tmp, map<char, string> &keys,
         vector<string> &res)
{
    int cur_len = (int) tmp.length();  //已搜索到的其中一种组合方式的长度
    if (cur_len == digits.length()) {  //该长度等于digits的长度,说明该组合下的搜索完成
        res.push_back(tmp);
        return ;
    }
    else {
        int i;
        int len = (int) keys[digits[cur_len]].length();
        for (i = 0; i < len; ++i) {
            tmp.push_back(keys[digits[cur_len]][i]);
            dfs(digits, tmp, keys, res);
            tmp.pop_back();  //回溯的过程
        }
    }
}

vector<string> letter_combinations(const string &digits)
{
    vector<string> res;
    if (digits.length() < 1) {  //没有按下任何数字键
        return res;
    }

    string tmp("");
    map<char, string> keys;  //map用于记录2-9的数字按键上对应的英文字母
    keys['2'] = string("abc");
    keys['3'] = string("def");
    keys['4'] = string("ghi");
    keys['5'] = string("jkl");
    keys['6'] = string("mno");
    keys['7'] = string("pqrs");
    keys['8'] = string("tuv");
    keys['9'] = string("wxyz");

    dfs(digits, tmp, keys, res);

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值