Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[LeetCode] Javascript Fib Function 2 Solution #157

Open
plh97 opened this issue Aug 5, 2020 · 0 comments
Open

[LeetCode] Javascript Fib Function 2 Solution #157

plh97 opened this issue Aug 5, 2020 · 0 comments
Assignees
Labels
algorithm algorithm

Comments

@plh97
Copy link
Owner

plh97 commented Aug 5, 2020

题目

image

From Bottom To Top

自底向上方式解决fib问题

Runtime: 60 ms, faster than 96.82% of JavaScript online submissions for Fibonacci Number.
Memory Usage: 36.7 MB, less than 9.38% of JavaScript online submissions for Fibonacci Number.

var fib = function(N) {
    const map = {
        0:0,
        1:1,
        2:1
    }
    for (let i=3;i<=N;i++) {
        map[i] = map[i-1] + map[i-2]
    }
    return map[N]
}

From Top To Bottom

自顶向下方式解决fib问题

Runtime: 864 ms, faster than 5.10% of JavaScript online submissions for Fibonacci Number.
Memory Usage: 44.1 MB, less than 5.47% of JavaScript online submissions for Fibonacci Number.

var fib = function(N) {
    const map = new Map()
    map.set(0,0)
    map.set(1,1)
    
    function run(N) {
        if (map.get(N)!=undefined) {
            return map.get(N)
        }else{
            map.set(N, fib(N-1) + fib(N-2))
            return map.get(N)
        }
    }
    return run(N)
};

dp 思路

上面两种也通常代表了, 动态规划的两种思路:

  • 自下而上, 常规思路, 通过化整为零的思路, 逐渐收敛问题,

  • 自上而下, 他通常就是利用 dp 以及状态机, 从1 开始, 一直到目标需要求解的 n , 通常有几个状态, 就代表 dp 有几层, 即 dp[状态 1][状态 2], 而上面这个问题, 仅仅只有一个状态就是n, 因此 dp 也仅仅只有一层.

Reference

labuladong - 动态规划解题套路框架

@plh97 plh97 added the algorithm algorithm label Aug 5, 2020
@plh97 plh97 self-assigned this Aug 5, 2020
@plh97 plh97 added C C computer language and removed C C computer language labels Aug 5, 2020
@plh97 plh97 changed the title JAVASCRIPT 2 SOLUTION Javascript Fib Function 2 Solution Aug 5, 2020
@plh97 plh97 closed this as completed Aug 5, 2020
@plh97 plh97 reopened this Aug 5, 2020
@plh97 plh97 changed the title Javascript Fib Function 2 Solution [LeetCode] Javascript Fib Function 2 Solution Oct 6, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
algorithm algorithm
Projects
None yet
Development

No branches or pull requests

1 participant