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.

Example

Input:Digit string "23"

Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].

思路

  • 思路1:
    • 使用两个队列完成,代码如下:
  • 思路2:
    • dfs

代码

class Solution {
public:
    vector<string> letterCombinations(string digits) {
		vector<string> res;
		int len = digits.size();
		if (len == 0) return res;

		string letters[] = {
			"abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"
		};
		queue<string> Que, QueTemp;
		int j = 0;
		for (int i = 0; i < len; ++i){
			if (digits[i] > '9' || digits[i] <= '1') return vector<string>();

			j = digits[i] - '2';

			if (Que.empty()){
				for (int k = 0; k < letters[j].size(); ++k){
					string tmp(charToString(letters[j][k]));
					Que.push(tmp);
				}
			}
			else{
				while (!Que.empty()){
					string tmp = Que.front();
					Que.pop();
					for (int k = 0; k < letters[j].size(); ++k){
						QueTemp.push(tmp + letters[j][k]);
					}
				}
				Que.swap(QueTemp);
			}
		}

		while (!Que.empty()){
			res.push_back(Que.front());
			Que.pop();
		}

		return res;
	}

	string charToString(char c){
		string res;
		stringstream ss;
		ss << c;
		ss >> res;
		return res;
	}
};
class Solution {
public:	
    vector<string> letterCombinations(string digits) {
		vector<string> res;
		int len = digits.size();
		if (len == 0) return res;
		string letters[] = {
			"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"
		};

		string path;
		dfs(res, digits, path, 0, letters);

		return res;
	}

	void dfs(vector<string> &res, string& digits, string path, int index, string letters[]){
		if (index == digits.size()){
			res.push_back(path);
			return;
		}

		for (int i = 0; i < letters[digits[index] - '0'].size(); ++i){
			dfs(res, digits, path + letters[digits[index] - '0'][i], index + 1, letters);
		}
	}
};
posted @ 2017-05-07 19:29  JeffLai  阅读(137)  评论(0编辑  收藏  举报