码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode: Letter Combinations of a Phone Number

时间:2015-04-13 09:24:58      阅读:142      评论:0      收藏:0      [点我收藏+]

标签:

Title:

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"].

简单的DFS搜索
class Solution {
public:
    map<int,string> digitsMap;
    Solution(){
        digitsMap[0]="";
        digitsMap[1]="";
        digitsMap[2] = "abc";
        digitsMap[3] = "def";
        digitsMap[4] = "ghi";
        digitsMap[5] = "jkl";
        digitsMap[6] = "mno";
        digitsMap[7] = "pqrs";
        digitsMap[8] = "tuv";
        digitsMap[9] = "wxyz";
    }
    vector<string> letterCombinations(string digits) {
        vector<string> result;
        if (digits=="")
            return result;
        string ret = "";
        dfs(0,digits,ret,result);
        return result;
    }
    void dfs(int index, string s, string ret,vector<string>& result){
        if (index == s.size()){
            result.push_back(ret);
            return ;
        }
        string tmp = digitsMap[s[index]-0];
        for (int i = 0 ; i < tmp.size(); i++){
            ret.push_back(tmp[i]);
            dfs(index+1,s,ret,result);
            ret.pop_back();
        }
        if (index == 0)
            return ;
    }
};

 

LeetCode: Letter Combinations of a Phone Number

标签:

原文地址:http://www.cnblogs.com/yxzfscg/p/4421292.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!