Skip to content

Commit

Permalink
添加(0509.斐波那契数.md):增加javascript版本优化空间复杂度到O(1)解法
Browse files Browse the repository at this point in the history
  • Loading branch information
Damon0820 committed May 27, 2022
1 parent 654bf61 commit 4e95d66
Showing 1 changed file with 18 additions and 0 deletions.
18 changes: 18 additions & 0 deletions problems/0509.斐波那契数.md
Original file line number Diff line number Diff line change
Expand Up @@ -234,6 +234,7 @@ func fib(n int) int {
}
```
### Javascript
解法一
```Javascript
var fib = function(n) {
let dp = [0, 1]
Expand All @@ -244,6 +245,23 @@ var fib = function(n) {
return dp[n]
};
```
解法二:时间复杂度O(N),空间复杂度O(1)
```Javascript
var fib = function(n) {
// 动规状态转移中,当前结果只依赖前两个元素的结果,所以只要两个变量代替dp数组记录状态过程。将空间复杂度降到O(1)
let pre1 = 1
let pre2 = 0
let temp
if (n === 0) return 0
if (n === 1) return 1
for(let i = 2; i <= n; i++) {
temp = pre1
pre1 = pre1 + pre2
pre2 = temp
}
return pre1
};
```

TypeScript

Expand Down

0 comments on commit 4e95d66

Please sign in to comment.