Letter Combinations of a Phone Number

Given a digit string, return all possible letter combinations that the number could represent.

这里用递归,递归式举例:\(f(2)=[a,b,c]\), \(f(23)=[a+f(3),b+f(3),c+f(3)]\), \(d+f(2)={[da,db,bc]}\)

下为C++代码

class Solution {
public:
    vector<string> letterCombinations(string digits) {
        vector<string> res;
        int length_digits=digits.size();
        if(length_digits<=1){
          res=num_let(digits);
        }
        else{
          vector<string> r=num_let(digits.substr(0,1));
          string sub_str=digits.substr(1);
          vector<string> temp_res=letterCombinations(sub_str);
          for(string s:r){
            for(string ss: temp_res){
              res.push_back(s+ss);
            }
          }
        }
        return res;
    }
    vector<string> num_let(string digit){ // tu ban fa 
      int n=atoi(digit.c_str());   // string -> int
      //int n=boost::lexical_cast<int>(digit); //#include "boost/lexical_cast.hpp" // 需要包含的头文件
      switch (n) {
        case 2:
          return {"a","b","c"};break;
        case 3:
          return {"d","e","f"};break;
        case 4:
          return {"g","h","i"};break;
        case 5:
          return {"j","k","l"};break;
        case 6:
          return {"m","n","o"};break;
        case 7:
          return {"p","q","r","s"};break;
        case 8:
          return {"t","u","v"};break;
        case 9:
          return {"w","x","y","z"};break;
        default:
          return {""};break;
      }
    }
};

posted @ 2015-02-18 13:00  clq.lib  阅读(148)  评论(0编辑  收藏  举报