C++ 从数字数组中查找可能的字母字符串数
给定字符串C++ 从数字数组中查找可能的字母字符串数,c++,arrays,string,recursion,C++,Arrays,String,Recursion,给定字符串12345和字母到数字的映射,如a=1,b=2,y=25,z=26;编写代码,从给定字符串中查找可能的字母字符串数 E.x.string12345从映射{12-3-4-5,1-23-4-5,1-2-3-4-5}中有可能的字母字符串为{lcde,awde,abcde} 我大致知道怎么做。我想它是递归的。查看第一个数字,将其字符映射添加到结果中,然后使用子数组(1,size-1)递归。同时查看前两位数字,看看它们是否,这类似于断字问题。您可以使用相同的方法来解决它。您可以使用记忆来减少总体
12345
和字母到数字的映射,如a=1
,b=2
,y=25
,z=26
;编写代码,从给定字符串中查找可能的字母字符串数
E.x.string12345
从映射{12-3-4-5,1-23-4-5,1-2-3-4-5}
中有可能的字母字符串为{lcde,awde,abcde}
我大致知道怎么做。我想它是递归的。查看第一个数字,将其字符映射添加到结果中,然后使用子数组(1,size-1)递归。同时查看前两位数字,看看它们是否,这类似于断字问题。您可以使用相同的方法来解决它。您可以使用记忆来减少总体运行时间。如果您在给定的示例中看到:
12-3-4-5, 1-23-4-5, 1-2-3-4-5
4和5会重复,你会一次又一次地计算。您可以在第一次计算时存储给定索引的排列,并在以后访问同一索引时使用它
伪代码:
recursive_function(string,index)
if you have already calculated values for this index in previous call
return value
recursive_function(string,index+1)
if possible
recursive_function(string,index+2)
store this value for future use.
详细信息:
recursive_function(string,index)
if you have already calculated values for this index in previous call
return value
recursive_function(string,index+1)
if possible
recursive_function(string,index+2)
store this value for future use.
当您对say index
i
进行递归调用时,当您完成此调用(基本上从当前递归返回)时,您已经使用/计算/找到了所有可能的值(从indexi
开始的子字符串的所有排列)。您可以存储这些值,因为如果您看到可能会有一些时候,您会再次从其他索引(比如j)中找到索引i
(j),只要完成此编码,想法来自@dream\u机器
基本上,这是一个回溯算法,复杂度是O(2n!),
需要一直跟踪左侧
,以知道应该将字符串放入输出
似乎算法太慢了,可能需要添加一些备忘录来加快速度
void helper(int start, string &s, string &path, vector<string> &result, int);
vector<string>
getPossibleCombo(string &s) {
vector<string> result;
string path;
helper(0, s, path, result, s.size());
return result;
}
void helper(int start, string &s, string &path, vector<string> &result, int left) {
if (start == s.size() && left == 0) {
result.push_back(path);
return;
}
for (int i = start; i < s.size(); i++) {
path.push_back('a' + (s[i] - '0') - 1);
helper(i + 1, s, path, result, left - 1);
path.pop_back();
if (i < s.size() - 1 && s[i] > '0' && s[i] <= '2') { // can try two.
if (s[i] == '2' && s[i+1] > '6')
continue;
int c = (s[i] - '0') * 10 + s[i + 1] - '0';
path.push_back('a' + c - 1);
helper(i + 2, s, path, result, left - 2);
path.pop_back();
}
}
}
int main() {
string s("12345");
auto r = getPossibleCombo(s);
for (auto &s : r) {
cout << s << endl;
}
}
你忘了问问题,但分数是2:)我不知道12345
如何映射到lcde
。你能解释一下这个系统吗?也许,通过清晰地解释这个系统,你不仅可以让别人告诉你怎么做,还可以启发你自己。;-)l=12,c=3,d=4,e=5不确定你所说的“在当前指数下尽可能计算”是什么意思@saleeeen请看我的更新。我补充了一些细节。我希望现在清楚了