我正在嘗試在我的遞回函式中使用 map(作為 DP 的實作)。在這里,我寫了一個簡單的斐波那契函式(我知道我可以在這里使用一個普通陣列,但我想知道我可以在其他函式中使用它,這些函式將接受更復雜的輸入,如對、字串、物件等)。
#include <bits/stdc .h>
using namespace std;
#define int long long
int fib(int n, map<int, int> &memo); // What I did
/* What I want:
Instead of pulling an external map as an argument,
the function will automatically create an empty map as a default parameter at the first call
and pass it by reference in the recursive calls. */
/* I tried some stuff
int fib(int n, map<int,int> memo={}); // Slow
int fib(int n, map<int, int> &memo, bool reset); // Works, but I want to know if there are any better idea which doesn't take 3 inputs
int fib(int n, map<int, int> &memo={}); // Doesn't compile (my target is something close to this)
*/
signed main()
{
map<int,int> mp; // Needs to be empty before being passed to fib()
int n;
cin >> n;
cout << n << ' ' << fib(n, mp); // I want to use just fib(n)
return 0;
}
int fib(int n, map<int, int> &memo) // The external memo needs to be empty
{
if(n==!!n) return n;
if(memo.find(n)!=memo.end()) return memo[n];
if(n<0)
{
if(n%2) return fib(-n, memo);
return -fib(-n, memo);
}
memo[n]=fib(n-1, memo) fib(n-2, memo);
return memo[n];
}
我想知道是否有任何方法可以在 C 中實作空映射引數。
uj5u.com熱心網友回復:
您可以簡單地多載該函式:
int fib(int n)
{
std::map<int, int> map;
fib(n, map);
}
int fib(int n, map<int, int> &memo) { ... }
這是你想要達到的嗎?
旁注:您應該洗掉#define int long long,它不是合法的 C 并且完全令人困惑。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/412925.html
標籤:
上一篇:使用稀疏矩陣表示聚類二值影像
