码迷,mamicode.com
首页 > 其他好文 > 详细

Dynamic Programming

时间:2020-01-24 09:28:30      阅读:77      评论:0      收藏:0      [点我收藏+]

标签:his   int   ogr   font   return   rom   style   uri   mem   

0. 

1. examples:

def fib(n):

  if n == 1 or n == 2:

    result = 1

  else 

     result = fib(n-1) + fib(n-2)

  return result

this is very in-efficient, O(2^n), and we use the following solution, which is called memoized solution

def fib(n, memo):

  if memo[n] != null:

    return memo[n]

  if n ==1 or n ==2:

    result = 1

  else 

    result = fib(n-1, memo) + fib(n-2, memo)

  memo[n] = result

  return result

Memo is an array, store memo = {1, 1, 2, 3, 5, 8 ,...}

def fib_bottom_up(n):

  if n ==1 or n ==2: 

    return 1

  bottom_up = new int[n+1]

  bottom_up[1] =1

  bottom_up[2] =1

  for i from 3 to n:

    bottom_up[i] = bottom_up[i-1] + bottom[i-2]

  return bottom_up[n]

Dynamic Programming

标签:his   int   ogr   font   return   rom   style   uri   mem   

原文地址:https://www.cnblogs.com/sarah-zhang/p/12231816.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!