【LeetCode】LeetCode——第17题:Letter Combinations of a Phone Number

17. Letter Combinations of a Phone Number

    My Submissions
Total Accepted: 78356  Total Submissions: 272852  Difficulty: Medium

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


















题目的大概意思是:给定一个数字字符串(数字为0-9),请按手机的9宫格输入法得到所有可能的字母组合(上面举了个列子)。

这道题难度等级:中等

思路:这个题看样子就是要用递归的节奏。先做一个索引表,将0-9的数字与其代表的字母对应起来,然后使用递归来做。

代码如下:

class Solution {
public:
    vector<string> letterCombinations(string digits) {
		vector<string> ans;
		if (digits.size() > 0){
			vector<string> tmp = letterCombinations(digits.substr(1, digits.size() - 1));
			if (tmp.size() == 0){
				tmp.push_back("");
			}
			for (int i = 0; i < index[digits[0] - '0'].length(); ++i){
				for (int j = 0; j < tmp.size(); ++j){
					ans.push_back(index[digits[0] - '0'][i] + tmp[j]);
				}
			}
		}
		return ans;
    }
    vector<string> index = {"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};//列表初始化
};
在这个代码中,倒数第二行的列表初始化是C++11.0以后的特性,现在的编译器可能有些不支持,想自己跑一下代码的得做一点点改动。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值