Letter Combinations of a Phone Number

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.

class Solution {
    void dsf(string keyStrs[],string& digits,int digitsSize,int pos,vector<string>& res,string &oneOfRes)
    { 
        if(digitsSize == 0){
            return ;
        }
        if(pos==digitsSize){
            res.push_back(oneOfRes);
            return;
        }
        string keyStr=keyStrs[digits[pos] - '0'];
        int keyStrSize = keyStr.size();
        for(int j=0;j<keyStrSize;j++){
            oneOfRes.push_back(keyStr[j]);
            dsf(keyStrs,digits,digitsSize,pos+1,res,oneOfRes);
            oneOfRes.pop_back();
        }
    }
public:
    vector<string> letterCombinations(string digits) {
        string keyStrs[]={"","","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"};
        vector<string> res;
        string oneOfRes;
        int digitsSize = digits.size();
        dsf(keyStrs,digits,digitsSize,0,res,oneOfRes);
        return res;
    }
};

 

posted @ 2015-12-06 22:17  zengzy  阅读(251)  评论(0编辑  收藏  举报
levels of contents