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

leetcode第一刷_Letter Combinations of a Phone Number

时间:2014-05-15 01:42:26      阅读:264      评论:0      收藏:0      [点我收藏+]

标签:c++   leetcode   算法   

水题。数字一共就9个,去掉1是用来显示标点的,剩下8个。

穷举一下map,然后有几个数字,就输出这几个数字的排列,是一个dfs嘛。

map<char, string> num;


void allCombinations(string &digits, int start, int len, string &pres, vector<string> &res){
        if(len == digits.length()){
            res.push_back(pres);
            //cout<<pres<<endl;
            return;
        }
        for(int i=0;i<num[digits[start]].length();i++){
            pres[len] = num[digits[start]][i];
            allCombinations(digits, start+1, len+1, pres, res);
        }
}


class Solution {
public:
    vector<string> letterCombinations(string digits) {
        vector<string> res;
        if(digits.length()<=0){
            res.push_back("");
            return res;
        }
        num[‘2‘] = "abc";
		num[‘3‘] = "def";
		num[‘4‘] = "ghi";
		num[‘5‘] = "jkl";
		num[‘6‘] = "mno";
		num[‘7‘] = "pqrs";
		num[‘8‘] = "tuv";
		num[‘9‘] = "wxyz";
        string pres(digits.length(),‘#‘);
        allCombinations(digits, 0, 0, pres, res);
        return res;
    }
};


leetcode第一刷_Letter Combinations of a Phone Number,布布扣,bubuko.com

leetcode第一刷_Letter Combinations of a Phone Number

标签:c++   leetcode   算法   

原文地址:http://blog.csdn.net/u012792219/article/details/25832399

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