`
cozilla
  • 浏览: 91885 次
  • 性别: Icon_minigender_1
  • 来自: 南京
社区版块
存档分类
最新评论

[Leetcode] Letter Combinations of a Phone Number

 
阅读更多
Letter Combinations of a Phone NumberJan 27 '124852 / 14644

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

这题有点诡异,如果没有res.clear(),vector中会多一个“”。

 

 

char m[10][5] = {" ","", "abc","def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
class Solution {
public:
    vector<string> res;
    int len;

    vector<string> letterCombinations(string digits) {
        len = digits.size();
        char *c = new char[len+1];
        c[len] = '\0';
        res.clear();
        gen(digits, 0, c);
        return res;
    }
    
    void gen(const string& num, int cur, char *c) {
        if (cur == len) {
            res.push_back(c);
            return;
        }
        char *s = &(m[num[cur] - '0'][0]);
        while (*s != '\0') {
            c[cur] = *s;
            gen(num, cur+1, c);
            s++;
        }
    }
};

 

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics