LeetCode 17 - Letter Combinations of a Phone Number

一、问题描述

Description:

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.

For example:

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.

给定一个由数字字符组成的字符串,根据电话按键上每个数字与字母的对应关系(如上图所示),求该数字字符串可能代表的所有字母组合。


二、解题报告

这里采用的思路比较简单,就是递归

class Solution {
    static string letter[10];
    vector<string> res;
public:
    vector<string> letterCombinations(string digits) {
        if(digits.empty())
            return res;
        string str;
        combine(digits, 0, str);
        return res;
    }

    void combine(string &digits, int i, string str) {
        if(i>=digits.size()) {   // 递归终止条件
            res.push_back(str);
            return;
        }
        string s = letter[digits[i]-'0'];
        for(int j=0; j<s.size(); ++j)
            combine(digits, i+1, str+s[j]);     
    }
};

string Solution::letter[] = {"","","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"};

AC 时间 0ms.





LeetCode答案源代码:https://github.com/SongLee24/LeetCode


posted @ 2015-05-20 11:25  神奕  阅读(144)  评论(0编辑  收藏  举报