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

[LeetCode] Letter Combinations of a Phone Number

时间:2014-12-11 00:12:47      阅读:297      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   io   ar   color   os   sp   for   

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.

bubuko.com,布布扣

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.

 

好长时间没练题了,最近比较懒加之工作略忙,疏于思考,浪费了很多时间。这题想来想去知道是要深搜,但是都没动手实现,以为很复杂,其实是很典型的DFS模板,这和 Sudoku solver 的思路基本没有差别(其实和所有类似的题型都没差,几乎都用DFS模板一套就能出来)

void comboIter(string digits, int i, vector<string> &domains, string cur, vector<string> &result) {
    if (i >= digits.size()) {
        result.push_back(cur);
        return;
    }
    char t = digits.at(i);
    string domain = domains[t-0];
    string old = cur;
    for (char ele : domain) {
        cur += ele;
        comboIter(digits, i+1, domains, cur ,result);
        cur = old;
    }
}

vector<string> letterCombinations(string digits) {
    vector<string> ret;
    if (!digits.size()) return {""};
    vector<string> domain = {"0","1","abc","def","ghi","jkl","mno","pqr","stu","vwxyz"};
    comboIter(digits,0,domain,"",ret);
    return ret;
}

 

[LeetCode] Letter Combinations of a Phone Number

标签:style   blog   http   io   ar   color   os   sp   for   

原文地址:http://www.cnblogs.com/agentgamer/p/4156601.html

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