File tree 1 file changed +42
-1
lines changed
1 file changed +42
-1
lines changed Original file line number Diff line number Diff line change @@ -366,4 +366,45 @@ PS:为啥 `dp` 数组初始化为 `amount + 1` 呢,因为凑成 `amount` 金
366
366
< img src=" ../pictures/qrcode.jpg" width=200 >
367
367
< / p>
368
368
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
+ ```
You can’t perform that action at this time.
0 commit comments