leetCode 17. Letter Combinations of a Phone Number

#include <iostream>
#include <vector>
#include <stdlib.h>
using namespace std;
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
class Solution {
public:
    vector<char> mystack;
    vector<string> ans;
   
    void getAns(string digits,string dict[]){
         
      if(digits.size()!=0){
       //char ch=digits.at(0);
       //int cur = atoi(ch);这样写有问题会报runtime error
       //
int cur =atoi(&ch);//此处atoi(&ch)会越界,因为字符串是以'\0'结尾,而这个字符在老后面会越界,某些编译器可能不会检查这个错误;
char ch[2] ;
            ch[0]= digits.at(0);
            ch[1]=0;
            int cur =atoi(ch);
            cur-=2;
            for(int i=0;i <dict[cur].size();++i){
                mystack.push_back(dict[cur].at(i));
                getAns(digits.substr(1),dict);
                mystack.pop_back();

            } 
      }else{
          string str="";
          for(int j=0;j<mystack.size();j++){
              str+=mystack[j];
          }
          ans.push_back(str);
         // mystack.pop_back();
      }
        
        
    }
    vector<string> letterCombinations(string digits) {
         string dict[8]= {"abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
        if(digits.size()==0){
            return ans;
        }
        
        getAns(digits,dict);
        return ans;
        
        
    }
};
int main(int argc, char** argv) {
    Solution so;
    so.letterCombinations("234");
    for(int i=0;i<so.ans.size();i++){
        cout<<so.ans[i]<<endl;
    }
    return 0;
}

 

posted on 2017-08-14 21:01  达达123567  阅读(84)  评论(0编辑  收藏  举报

导航