【发布时间】:2021-12-10 13:12:05
【问题描述】:
我不知道为什么,但是当递归尝试添加值然后返回它时,函数返回后的映射删除了所有元素,我不明白这是什么问题。
static int SumNum(string target, string m[], map<string, int> memo = {}){
if (memo.find(target) != memo.end()) {
cout << memo.find(target)->second<<"\n";
return memo.find(target)->second;
}
if (target == "") return 1;
int totalCount = 0;
for(auto i = 0;i < 10; i++)
{
if (target.find(m[i]) == 0){
int numOfWays = SumNum(target.substr(m[i].length()),m,memo);
totalCount += numOfWays;
}
}
memo.emplace(target, totalCount);
return totalCount;
}
int main(){
string ar[10] = {"e","ee","eee","eeee","eeeee","eeeeee","f","fdc","d","c"};
string target = "eeeeeeeeefdc";
auto answer = SumNum(target,ar);
cout << answer;
}
【问题讨论】:
-
可能通过引用传递地图?
-
你知道按值传递参数和按引用传递参数的区别吗?
-
@Max 不,如何在我的代码中做到这一点?
-
引用是 C++ 中的一个基本概念。你应该读一本好的 C++ 书籍The Definitive C++ Book Guide and List
标签: c++ dictionary recursion