首页 > 学院 > 开发设计 > 正文

Letter Combinations of a Phone Number问题及解法

2019-11-06 06:03:22
字体:
来源:转载
供稿:网友

问题描述:

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

问题分析:

这可以看作一个组合问题

1.设置一个结果集result值为空

2.对每个digit进行遍历,将其对应的字符添加分别与result结果集中的每个元素组合即可

下面是具体实现:

class Solution {public:    vector<string> letterCombinations(string digits) {        vector<string> result;        	if(digits.empty()) return vector<string>();        	vector<string> v = {"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};        	result.push_back("");        	        	for(int i = 0; i  < digits.size(); i++)        	{        		int num = digits[i] - '0';        		if(num < 0 || num > 9) break;        		string candidate = v[num];        		if(candidate.empty()) continue;//出现数字0和1         		vector<string> tmp;				// 将result和candidate的字符串组合一下 				for(int j = 0 ; j < candidate.size() ; j++) {            		for(int k = 0 ; k < result.size() ; k++) {                		tmp.push_back(result[k] + candidate[j]);            		}        		}				result.swap(tmp); 			}			return result;    }};好了,就先记这么多吧~


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表