LeetCode No.17 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"].

=================================================================

題目鏈接:https://leetcode.com/problems/letter-combinations-of-a-phone-number/

題目大意:求出一串數字對應九鍵鍵盤所有可能字符組合。

思路:遞歸。

ans = 第一個字符所有組合 X叉乘 後面n-1個字符的所有組合

參考代碼:

class Solution {
public:
    vector<string> letterCombinations(string digits) {
        vector <string> ans ;
        int n = digits.size() ;
        if ( n == 0 )
            return ans ;
        for ( int i = 0 ; i < n ; i ++ )
            if ( digits[i] == '0' || digits[i] == '1' )
                return ans ;
        vector <string> nums = { "" , "" , "abc" , "def" , "ghi" , "jkl" , "mno" , "pqrs" , "tuv" , "wxyz" } ;
        return combination ( digits , nums ) ;
    }
    vector <string> combination ( string digits , vector <string>& nums )
    {
        vector <string> ans ;
        int n = digits.size() ;
        if ( n > 1 )
        {
            vector <string> str = combination ( digits.substr ( 1 ) , nums ) ;
            string s = "" ;
            for ( int i = 0 ; i < nums[digits[0]-'0'].size() ; i ++ )
            {
                for ( int j = 0 ; j < str.size() ; j ++ )
                {
                    s += nums[digits[0]-'0'][i] ;
                    s += str[j] ;
                    ans.push_back ( s ) ;
                    s = "" ;
                }
            }
        }
        else
        {
            string s = "" ; 
            for ( int i = 0 ; i < nums[digits[0]-'0'].size() ; i ++ )
            {
            	s += char ( nums[digits[0]-'0'][i] ) ; 
            	ans.push_back ( s ) ;
            	s = "" ; 
			}
        }
        return ans ;
    }
};



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