LeetCode 017. Letter Combinations of a Phone Number

Letter Combinations of a Phone Number

 

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

Note:
Although the above answer is in lexicographical order, your answer could be in any order you want.

這道題看似不難,但是卻不好下手。最直觀的思路是播了多少位號碼,就用多少個for循環,遍歷每位號碼對應的字符串。但是我們是無法得知會有多少位號碼的,那麼最好的辦法是用遞歸,這隻退出條件。

下面是代碼,但是這裏需要注意:temp變量在遞歸完後必須將遞歸一次新增的一個字符給去掉。其實我也很有疑問,不是說形參無法傳值給實參麼?怎麼遞歸後temp值不是保存遞歸前的值,而是將遞歸中改變的值返回來了?求大神解釋!

const string letters[10] = {" ", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};

class Solution 
{
public:
    vector<string> result;
    void aletter(string digits, string temp)
    {
        if(!digits.length())
        {
            result.push_back(temp);
        }
        else
        {
            int index = digits[0] - '0';
            for(int i=0; i<letters[index].length(); i++)
            {
				temp += letters[index][i];
                aletter(digits.substr(1),temp);
				temp = temp.substr(0,temp.length()-1);

            }
        }
    }
    
    vector<string> letterCombinations(string digits)
    {
        result.clear();
        aletter(digits, "");
        return result;
    }

};

另外我還在這裏看到了另一種比較簡潔的做法,貼上來。

vector<string> letterCombinations(string digits) 
{  
	// Start typing your C/C++ solution below	
	// DO NOT write int main() function  
	const string letters[] = {"abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"}; 
	
	vector<string> ret(1, "");  
	for (int i = 0; i < digits.size(); ++i) 
	{  
		for (int j = ret.size() - 1; j >= 0; --j) 
		{  
			const string &s = letters[digits[i] - '2'];			
			for (int k = s.size() - 1; k >= 0; --k) 
			{  
				if (k)  
					ret.push_back(ret[j] + s[k]); 				
				else  
					ret[j] += s[k];  
            }  
        }  
    }  
  
    return ret;  
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章