leetcode 17. Letter Combinations of a Phone Number

Given a string containing digits from 2-9 inclusive, 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. Note that 1 does not map to any letters.

Example:

Input: "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.

 

用迭代的方法来实现;

初始答案为ans=“”;

出现一个数字就把该数字对于按键上所有的字母和之前的组合依次相加,遍历输入字符串的每一个数字就能得到所有 的组合;

用数组num保存每一按键第一个字母在字母表中的位置, 方便计算

注意点:输入可能是空字符串,需要单独处理

 1 class Solution {
 2 public:
 3     vector<string> letterCombinations(string digits) {
 4         vector<string> ans;
 5         if(digits=="") return ans;
 6         ans.push_back("");
 7         char ch[]={'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'};
 8         int num[11]={0,0,0,3,6,9,12,15,19,22, 26};
 9         for(int i=0; i<digits.size(); i++){
10             vector<string> temp;
11             int cnt=num[digits[i]-'0'+1] - num[digits[i]-'0'], idx=num[digits[i]-'0'];
12             for(int j=0; j<ans.size(); j++){
13                 for(int k=0; k<cnt; k++) temp.push_back(ans[j]+ch[idx+k]);
14             }
15             ans = temp;
16         }
17         return ans;
18     }
19 };

 

posted @ 2018-06-24 14:32  赖兴宇  阅读(190)  评论(0)    收藏  举报