本文主要是介绍[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;}//ifvector<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];}//forvec.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;}//forreturn 0;
}
【代码二】
class Solution {
public:vector<string> letterCombinations(string digits) {vector<string> result;DFS(digits,0,"",result);return result;}
private:void DFS(string digits,int cur,string path,vector<string> &result){string keyboard[] = {" ","","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"};if(cur == digits.length()){result.push_back(path);return;}//ifint len = keyboard[digits[cur] - '0'].length();for(int i = 0;i < len;++i){char c = keyboard[digits[cur] - '0'][i];DFS(digits,cur + 1,path + c,result);}//for}
};
注意一种特殊情况:
这篇关于[LeetCode]17.Letter Combinations of a Phone Number的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!