codementor on Nostr: Learn: From recursion to memoization Plain recursive Fibonacci recomputes the same ...
Learn: From recursion to memoization
Plain recursive Fibonacci recomputes the same values again and again: O(2ⁿ). Remember each answer the first time, and every value is computed once: O(n).
```csharp
var memo = new Dictionary<int, long>();
Console.WriteLine(Fib(60));
long Fib(int n)
{
if (n < 2) return n;
if (memo.TryGetValue(n, out long known)) return known;
return memo[n] = Fib(n - 1) + Fib(n - 2);
}
```
It prints 1548008755920 at once. Plain recursion would take hours for n = 60.
This is the first step of dynamic programming: overlapping subproblems + a cache.
Read more:
https://www.geeksforgeeks.org/dsa/recursion-algorithms/#tip · TIP-097
Published at
2026-10-26 06:37:56 UTCEvent JSON
{
"id": "28514a6de8ca969e1a9c968a5da8438ad8b56a00473219c1aff184379debe91b",
"pubkey": "e68a0856e90d9997b1f721e905249896412dd570399a987b2e8fd5e7fcfe2279",
"created_at": 1792996676,
"kind": 1,
"tags": [
[
"t",
"tip"
]
],
"content": "Learn: From recursion to memoization\n\nPlain recursive Fibonacci recomputes the same values again and again: O(2ⁿ). Remember each answer the first time, and every value is computed once: O(n).\n\n```csharp\nvar memo = new Dictionary\u003cint, long\u003e();\nConsole.WriteLine(Fib(60));\nlong Fib(int n)\n{\n if (n \u003c 2) return n;\n if (memo.TryGetValue(n, out long known)) return known;\n return memo[n] = Fib(n - 1) + Fib(n - 2);\n}\n```\n\nIt prints 1548008755920 at once. Plain recursion would take hours for n = 60.\nThis is the first step of dynamic programming: overlapping subproblems + a cache.\n\nRead more: https://www.geeksforgeeks.org/dsa/recursion-algorithms/\n\n#tip · TIP-097",
"sig": "4eae65683815c16de74087026c91b26a723ee00c479e080561fb7989d683b84294c2421d5707a58346df4966834baa501410beb36280863eb33702ad97fb39b8"
}