【LeetCode】17. 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循環。

舉例:

初始化排列{""}

1、輸入2,代表"abc"

已有排列中只有字符串"",所以得到{"a","b","c"}

2、輸入3,代表"def"

(1)對於排列中的首元素"a",刪除"a",並分別加入'd','e','f',得到{"b","c","ad","ae","af"}

(2)對於排列中的首元素"b",刪除"b",並分別加入'd','e','f',得到{"c","ad","ae","af","bd","be","bf"}

(2)對於排列中的首元素"c",刪除"c",並分別加入'd','e','f',得到{"ad","ae","af","bd","be","bf","cd","ce","cf"}

注意

(1)每次添加新字母時,應該先取出現有ret當前的size(),而不是每次都在循環中調用ret.size(),因為ret.size()是不斷增長的。

(2)刪除vector首元素代碼為:

ret.erase(ret.begin());

 

 

class Solution {
public:
    vector<string> letterCombinations(string digits) {
        vector<string> ret;
        if(digits == "")
            return ret;
            
        ret.push_back("");
        
        vector<string> dict(10); //0~9
        dict[2] = "abc";
        dict[3] = "def";
        dict[4] = "ghi";
        dict[5] = "jkl";
        dict[6] = "mno";
        dict[7] = "pqrs";
        dict[8] = "tuv";
        dict[9] = "wxyz";
        
        for(int i = 0; i < digits.size(); i ++)
        {
            int size = ret.size();
            for(int j = 0; j < size; j ++)
            {
                string cur = ret[0];
                ret.erase(ret.begin());
                for(int k = 0; k < dict[digits[i]-'0'].size(); k ++)
                {
                    ret.push_back(cur + dict[digits[i]-'0'][k]);
                }
            }
        }
        return ret;
    }
};


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM