leetcode之Letter Combinations of a Phone Number

来源:互联网 发布:网络传播理论与实践 编辑:程序博客网 时间:2024/06/05 18:05

原题如下:

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"].
刚看到这道题确实有点儿不知所措,但在思考了之后发现这还是一个深度遍历的问题,针对digit的每一位,穷举其所有可能,然后依次深入,这相当于在深度遍历的同时兼顾广度。代码中用字符串数组来完成数字和字符的对应,字符想数字的转换减“2”是因为2所对应的字符串存在于下标为0 的字符串数组中。

class Solution {public:    vector<string> letterCombinations(string digits) {vector<string>v;string s;DFS(v,s,digits,0);return v;}  void DFS(vector<string>&v,string s,string digits,int index){if(index == digits.size()){v.push_back(s);return;}string ss[] = {"abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"};int c = digits[index] - '2';for(int i = 0; i < ss[c].length(); i++ ){s.push_back(ss[c][i]);DFS(v,s,digits,index + 1);s.pop_back();}}};
实现这道题没有参考别人的思路,AC的那一刻确实挺有成就感的,另外在用cout输出string时应该include<string>才行,感觉这样限制有点儿奇怪,因为其它情况都能识别string,唯独cout时需要加include<string>,这确实有点儿不太合理吧。。。

0 0
原创粉丝点击