首页 > 代码库 > [LeetCode]17.Letter Combinations of a Phone Number
[LeetCode]17.Letter Combinations of a Phone Number
【题目】
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.
【分析】
无
【代码】
/********************************* * 日期:2015-01-22 * 作者:SJF0115 * 题目: 17.Letter Combinations of a Phone Number * 网址:https://oj.leetcode.com/problems/letter-combinations-of-a-phone-number/ * 结果:AC * 来源:LeetCode * 博客: **********************************/ #include <iostream> #include <vector> using namespace std; class Solution { public: vector<string> letterCombinations(string digits) { vector<string> vec; if(digits.length() <= 0){ vec.push_back(digits); return vec; }//if vector<char> number; DFS(vec,digits,number); return vec; } private: void DFS(vector<string> &vec,string digits,vector<char> &number){ string letters[] = {" ","","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"}; // 一种组合完成 int curLen = number.size(); if(curLen == digits.length()){ string letter; for(int i = 0;i < curLen;++i){ letter += number[i]; }//for vec.push_back(letter); return; }//if // 数字 int num = digits[curLen] - '0'; // 数字所对应的字母长度 int len = letters[num].length(); for(int i = 0;i < len;++i){ number.push_back(letters[num][i]); DFS(vec,digits,number); number.pop_back(); }//for } }; int main(){ Solution solution; string number = "2"; vector<string> result = solution.letterCombinations(number); // 输出 for(int i = 0;i < result.size();++i){ cout<<result[i]<<endl; }//for return 0; }
注意一种特殊情况:
[LeetCode]17.Letter Combinations of a Phone Number
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。