Skip to content

Commit 12fbf29

Browse files
agi-templarlabuladong
authored andcommitted
509 斐波那契数列 Python 3 解法
1 parent 372b92b commit 12fbf29

File tree

1 file changed

+42
-1
lines changed

1 file changed

+42
-1
lines changed

动态规划系列/动态规划详解进阶.md

Lines changed: 42 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -366,4 +366,45 @@ PS:为啥 `dp` 数组初始化为 `amount + 1` 呢,因为凑成 `amount` 金
366366
<img src="../pictures/qrcode.jpg" width=200 >
367367
</p>
368368

369-
======其他语言代码======
369+
======其他语言代码======
370+
371+
[DapangLiu](https://github.com/DapangLiu) 提供 509. 斐波那契数 Python3 解法代码:
372+
373+
递归写法
374+
375+
```python
376+
class Solution:
377+
def fib(self, N: int) -> int:
378+
if N <= 1:
379+
return N
380+
return self.fib(N-1) + self.fib(N-2)
381+
```
382+
383+
动态规划写法
384+
385+
```python
386+
class Solution:
387+
def fib(self, N: int) -> int:
388+
if N == 0:
389+
return 0
390+
# init
391+
result = [0 for i in range(N+1)]
392+
result[1] = 1
393+
394+
# status transition
395+
for j in range(2, N+1):
396+
result[j] = result[j-1] + result[j-2]
397+
return result[-1]
398+
```
399+
400+
动态规划写法 (状态压缩)
401+
402+
```python
403+
class Solution:
404+
def fib(self, n: int) -> int:
405+
# current status only depends on two previous status
406+
dp_0, dp_1 = 0, 1
407+
for _ in range(n):
408+
dp_0, dp_1 = dp_1, dp_0 + dp_1
409+
return dp_0
410+
```

0 commit comments

Comments
 (0)