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

Fibonacci Optimization #1050

Open
junxnone opened this issue Nov 19, 2021 · 0 comments
Open

Fibonacci Optimization #1050

junxnone opened this issue Nov 19, 2021 · 0 comments

Comments

@junxnone
Copy link
Owner

junxnone commented Nov 19, 2021

Reference

Brief

  • 问题描述:
    • 条件
      • 第一个月初有一对刚诞生的兔子
      • 第二个月之后,即第三个月初他们可以生育
      • 每月每对可生育的兔子会诞生下一对新兔子
      • 兔子永不死去
    • 问题: 假设在第N月共有兔子a对,第N+1月共有兔子b对,则N+2月该有多少对兔子?
image

Algos

递归法

  • 时间复杂度 O(2^n)
int fib(int n){
  if(n < 2) return n;
  return fib(n-1) + fib(n-2);
}

递推法

  • 时间复杂度 O(n)
  • 空间复杂度 O(n)
int fib(int n){
  int n_1 = 0, n_2 = 1;
  int tmp;
  for(int i = 2; i < n; i++){
    tmp = n_1;
    n_1 = n_2;
    n_2 += tmp;
  }
}

递推式

  • f(2) = f(1) + f(0)
  • f(3) = f(2) + f(1) = 2 * f(1) + f(0)
  • f(4) = f(3) + f(2) = 3 * f(1) + 2 * f(0)
  • ...
  • f(n) = f(n-1) + f(n-2) = A * f(1) + B * f(0)

image

  • 问题转化为 M ^ N 的优化
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant