论坛首页 编程语言技术论坛

[Leetcode] Letter Combinations of a Phone Number

浏览 2209 次
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
作者 正文
   发表时间:2013-08-14  
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