1、一个简单的动态规划;
lettercombination(string digits)
{
help(digits,i,len);
}
void help(string digits,int i,int len)
{
if(i==len)
{
str[len]='\0';
string temp=str;
res.push_back(temp);
return;
}
int j=digits[i]-'0';
for(int j=0;j<num[i].size();j++)
{
str[i]=num[i][j];
help(digits,i+1,len);
}
}
题目:
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.
思路:简单的动态规划思想
代码:
class Solution {
public:
vector<string> res;
string num[10];
char str[1000];
vector<string> letterCombinations(string digits) {
int len=digits.length();
res.clear();
num[2]="abc";
num[3]="def";
num[4]="ghi";
num[5]="jkl";
num[6]="mno";
num[7]="pqrs";
num[8]="tuv";
num[9]="wxyz";
help(digits,0,len);
return res;
}
void help(string &digits,int i,int len)
{
if(i==len)
{
str[len]='\0';
string temp=str;
res.push_back(temp);
return;
}
int n=digits[i]-'0';
for(int j=0;j<num[i].size();j++)
{
str[i]=num[n][j];
help(digits,i+1,len);
}
}
};