LeetCode——017

来源:互联网 发布:鲸鱼死后爆炸知乎 编辑:程序博客网 时间:2024/04/30 01:38

这里写图片描述
/*
17. Letter Combinations of a Phone Number My Submissions QuestionEditorial Solution
Total Accepted: 76784 Total Submissions: 269022 Difficulty: Medium
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.
*/
/*
解题思路:
此题采用深度遍历dfs
1.首先建立数字对应的字符串集合
2.深度遍历,每一层处理一个字符
3.当字符都遍历完后,即当字符串为空时,将当前累计的字符串放到结果集中

代码如下:
*/

class Solution {public:    vector<string> letterCombinations(string digits) {        //此题采用深度遍历即可        //先要简历对应数字的字符串集合        if(digits.empty())return {};        //建立字符串集合        vector<string> nums={"","","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"};        vector<string> res;        string out="";        dfs(digits,nums,out,res);        return res;    }    void dfs(string digits,vector<string>&nums,string out,vector<string>&res){        //判断结束        if(digits.empty()){            res.push_back(out);            return ;        }        //每一层取出一个字符来研究分析        int val=digits[0]-'0';        digits=digits.substr(1);        for(int i=0;i<nums[val].size();i++){            dfs(digits,nums,out+nums[val][i],res);        }    }};
0 0