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 16:37:57 UTCEvent JSON
{
"id": "bf7f6f2ea17576425237de59fd3630006af9c590f3847fdb37b7818dd7422df7",
"pubkey": "e68a0856e90d9997b1f721e905249896412dd570399a987b2e8fd5e7fcfe2279",
"created_at": 1793032677,
"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": "2831a20e1a3160448b974b5a700b24b3a13d06640ac56b8045ddb824b6d357e09822af4cc9219427f06d0c3c9998c62afb7e9010671fdb82da8e34b814c98c97"
}