LeetCode:Letter Combinations of a Phone Number

題目連接html

Given a digit string, return all possible letter combinations that the number could represent.git

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.編程

 


dfs遞歸解法app

class Solution {
public:
    vector<string> letterCombinations(string digits) {
        vector<string> res;
        string tmpres(digits.size(), ' ');
        dfs(digits, 0, tmpres, res);
        return res;
    }
    
    void dfs(const string &digits, int index, string &tmpres, vector<string>&res)
    {
        string numap[] = {" ","","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"};
        if(index == digits.size())
        {
            res.push_back(tmpres);
            return;
        }
        for(int i = 0; i < numap[digits[index] - '0'].size(); i++)
        {
            tmpres[index] = numap[digits[index] - '0'][i];
            dfs(digits, index+1, tmpres, res);
        }
    }
};

 


 

根據編程之美-3.2電話號碼對應英語單詞 中的代碼3-4,咱們有以下的非遞歸解法,實際上是把上述遞歸改成非遞歸spa

 1 class Solution {
 2 public:
 3     vector<string> letterCombinations(string digits) {
 4         vector<string>res;
 5         vector<int> ansIndex(digits.size(), 0);
 6         string numap[] = {" ","","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"};
 7         
 8         while(true)
 9         {
10             string tmp(digits.size(),' ');
11             for(int i = 0; i < digits.size(); i++)
12                 tmp[i] = numap[digits[i]-'0'][ansIndex[i]];
13             res.push_back(tmp);
14             int k = digits.size() - 1;
15             while(k >= 0)
16             {
17                 if(ansIndex[k] < numap[digits[k]-'0'].size() - 1)
18                 {
19                     ansIndex[k]++;
20                     break;
21                 }
22                 else 
23                 {
24                     ansIndex[k] = 0;
25                     k--;
26                 }
27             }
28             if(k < 0)break;
29         }
30         
31         return res;
32     }
33 };

 


 

bfs非遞歸解法(相似於求集合子集的算法2)                本文地址code

class Solution {
public:
    vector<string> letterCombinations(string digits) {
        vector<string> res(1,"");
        string numap[] = {" ","","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"};
        for(int i = 0; i < digits.size(); i++)
        {
            vector<string>tmp;
            for(int j = 0; j < res.size(); j++)
                for(int k = 0; k < numap[digits[i] - '0'].size(); k++)
                    tmp.push_back(res[j] + numap[digits[i] - '0'][k]);
            res = tmp;
        }
        
        return res;
    }
};

 

【版權聲明】轉載請註明出處:http://www.cnblogs.com/TenosDoIt/p/3771254.htmlhtm

相關文章
相關標籤/搜索