题目
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"].
分析
本题较为简单,适用于分治算法求解。可将原字符串分成长度相近的两个子串,则原问题变成两个规模为原来一班的子问题,算法复杂度递推公式为
T(n)=2T(n/2)+O(n^7)
算法复杂度为O(n^7)
代码
#include <iostream>
#include <string>
#include <vector>
using namespace std;
class Solution {
public:
vector<string> letterCombinations(string digits) {
string grid[8] = {"abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"};
vector<string> result;
int n = digits.size();
if (!n) return result;
if (n == 1)
{
for (int i = 0;i < grid[digits[0]-'0'-2].size();i++)
{
string s = "";
s += grid[digits[0]-'0'-2][i];
result.push_back(s);
}
return result;
}
vector<string> r2 = letterCombinations(digits.substr(0,n/2));
vector<string> r3 = letterCombinations(digits.substr(n/2));
for (int i = 0;i < r2.size();i++)
for (int j = 0;j < r3.size();j++)
result.push_back(r2[i]+r3[j]);
return result;
}
};