LEETCODE: Letter Combinations of a Phone Number

来源:互联网 发布:mac chrome插件导出 编辑:程序博客网 时间:2024/06/05 02:56
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.


使用递归来解决这个办法:

把当前字符的所有可能性记录下来,放到前面已经处理得到的字符上。对于未处理的,在我们找到的当前字符的所有可能的每一种可能性上,递归调用当前的函数,把新的已得到的字符串,新的未处理字符串传入。


char allChar[12] = {' ','%', 'a', 'd', 'g', 'j', 'm', 'p', 't', 'w', '+', '^'};int digital[12] = {1, 1, 3, 3, 3, 3, 3, 4, 3, 4, 1, 1};class Solution {public:   void letterCombinationsInternal(string digits, string preprocess, vector<string> &results) {      if(digits.length() == 0) {         results.push_back(preprocess);         return;      }      for(int jj = 0; jj < digital[digits[0] - '0']; jj ++) {          char newch = allChar[digits[0] - '0'] + jj;          string newpreprocess = preprocess + newch;          letterCombinationsInternal(digits.substr(1,digits.length() - 1), newpreprocess, results);      }   }   vector<string> letterCombinations(string digits) {      vector<string> results;      letterCombinationsInternal(digits, "", results);      return results;   }};


0 0
原创粉丝点击