1. 程式人生 > >【LeetCode & 劍指offer刷題】回溯法與暴力列舉法題5:Letter Combinations of a Phone Number

【LeetCode & 劍指offer刷題】回溯法與暴力列舉法題5:Letter Combinations of a Phone Number

【LeetCode & 劍指offer 刷題筆記】目錄(持續更新中...)

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"]. Note: Although the above answer is in lexicographical order, your answer could be in any order you want.

C++   //傳統手機數字盤的按鍵產生的所有可能字母組合 //感覺和回溯法沒有什麼關係,就是窮舉法 class Solution { public :     vector < string > letterCombinations
( string digits )     {         if ( digits . empty ()) return vector < string >(); //異常情況處理                 unordered_map < char , string > map =         {             { '2' , "abc" },             { '3' , "def" },             { '4' , "ghi" },             { '5' , "jkl" },             { '6' , "mno" },             { '7' , "pqrs" },             { '8' , "tuv" },             { '9' , "wxyz" }         };                 vector < string > result ;         result . push_back ( "" ); // add a seed for the initial case,因為之後會遍歷結果向量 push了一個空元素,result size變為1         for ( int i = 0 ; i < digits . size (); i ++) //遍歷數字, 如 2 3         {             if ( map . find ( digits [ i ]) == map . end ()) continue ; //如果不是2~9的數字,繼續迴圈                         string & candidate = map [ digits [ i ]]; //得到候選字元構成的字串             vector < string > temp ;             for ( string & ri : result ) //遍歷結果向量,如 "a" "b" "c"              {                for ( char ci : candidate ) //遍歷候選字元 如 "def"                {                    temp . push_back ( ri + ci );                }             }            // result = temp; //複製到結果向量             result . swap ( temp ); //交換,swap does not take memory copy         }         return result ;     } };