Leetcode letter-combinations-of-a-phone-number(DFS)

题目描述

给出一个仅包含数字的字符串,给出所有可能的字母组合。
数字到字母的映射方式如下:(就像电话上数字和字母的映射一样)
Input:Digit string "23"Output:["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].
注意:虽然上述答案是按字典序排列的,但你的答案可以按任意的顺序给出
 
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"].↵

Note: 

Although the above answer is in lexicographical order, your answer could be in any order you want.
 
思路:使用深度遍历
复制代码
class Solution {
public:
    vector<string> letterCombinations(string digits) {
        vector<string> dict{"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
        vector<string> res;
        int n = digits.size();
        string out;
        DFS(digits,0,dict,out,res);
        return res;
    }
    void DFS(string digits,int level, vector<string> dict,string &out, vector<string> &res)
    {
        if(level == digits.size())
            res.push_back(out);
        else
        {
            string s = dict[digits[level]-'0'];
            for(int i = 0;i<s.size();++i)
            {
                out.push_back(s[i]);
                DFS(digits,level+1,dict,out,res);
                out.pop_back();
            }
        }
    }
};
复制代码

 

posted @   鸭子船长  阅读(116)  评论(0编辑  收藏  举报
编辑推荐:
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
点击右上角即可分享
微信分享提示