Leetcode 17. Letter Combinations of a Phone Number

Given a string containing digits from 2-9 inclusive, 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. Note that 1 does not map to any letters.
在這裏插入圖片描述
Example:

Input: “23”
Output: [“ad”, “ae”, “af”, “bd”, “be”, “bf”, “cd”, “ce”, “cf”].

method 1

與permutation相似的思路,只是permutaion是從數組A向數組A遍歷,該題是從數組digits往數組chs遍歷

void helper(map<int, vector<char>> phoneNumber, string digits, int cur, string temp, vector<string>& ans){
	if (cur == digits.size()){
		ans.push_back(temp);
	}else{
		int num = digits[cur] - '0';
		vector<char> chs = phoneNumber[num];
		for (int i = 0; i < chs.size(); i++)
		{
			temp += chs[i];
			helper(phoneNumber, digits, cur + 1, temp, ans);
			temp.pop_back();
		}
	}
}

vector<string> letterCombinations(string digits) {
    vector<string> ans; 
    if(digits.size() == 0) return ans;
	map<int, vector<char>> phoneNumber;
	phoneNumber[2] = { 'a', 'b', 'c' };
	phoneNumber[3] = { 'd', 'e', 'f' };
	phoneNumber[4] = { 'g', 'h', 'i' };
	phoneNumber[5] = { 'j', 'k', 'l' };
	phoneNumber[6] = { 'm', 'n', 'o' };
	phoneNumber[7] = { 'p', 'q', 'r','s' };
	phoneNumber[8] = { 't', 'u', 'v' };
	phoneNumber[9] = { 'w', 'x', 'y','z' };

	helper(phoneNumber, digits, 0, "", ans);
	return ans;
}
發佈了93 篇原創文章 · 獲贊 9 · 訪問量 2萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章