Skip to content

Commit 84a2f8e

Browse files
committed
feat: add [509] 斐波那契数
1 parent 24d82e4 commit 84a2f8e

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed

509.斐波那契数.ts

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
/*
2+
* @lc app=leetcode.cn id=509 lang=typescript
3+
*
4+
* [509] 斐波那契数
5+
*/
6+
7+
// @lc code=start
8+
function fib(n: number): number {
9+
10+
const cacheMapping = new Map<number, number>()
11+
12+
const compute = (n: number) => {
13+
if (cacheMapping.has(n)) return cacheMapping.get(n)
14+
if (n === 0) {
15+
cacheMapping.set(n, 0)
16+
return 0
17+
}
18+
if (n <= 2) {
19+
cacheMapping.set(n, 1)
20+
return 1
21+
}
22+
23+
const prev = compute(n - 2)
24+
const next = compute(n - 1)
25+
26+
cacheMapping.set(n - 2, prev)
27+
cacheMapping.set(n - 1, next)
28+
29+
return prev + next
30+
}
31+
32+
return compute(n)
33+
};
34+
// @lc code=end
35+
36+
// 0 1 2 3 4
37+
// 0 1 1 2 3 5

0 commit comments

Comments
 (0)