序列二次规划_函数式的动态规划

2ed906960ba208e15c0536d2c24caeba.png

函数式的动态规划

动态规划是一类很常用的算法,在C/C++/Java中一般使用于数组进行记忆化。而函数式编程语言一般无法方便地操作数组这些依赖副作用的数据结构,函数式的记忆化便要另寻他法。

本文就是一个简单的笔记,用一些代码片段展示我所知的函数式动态规划的技巧。

(2020/5/17,时隔五个月后的更新,新增Memocombinators)

Course-of-Values Recursion

Course-of-Values Recursion是我认为最直观的一种技巧,就是将遍历过的结果当作返回值的一部分保留下来,在递归的时候可以取得运算过的值。

对于递归函数f,定义一个辅助的函数bar

则原递归函数f可以用bar表示出来:

斐波那契数列:

fibBar :: Int -> [Int]
fibBar 0 = [0]
fibBar 1 = 1:fibBar 0
fibBar n = let course = fibBar (n-1) in -- [fib(n-1)..fib(0)]
           let p  = course !! 0 in -- fib(n-1)
           let pp = course !! 1 in -- fib(n-2)
           p + pp : course

-- >>> fibBar 10
-- [55,34,21,13,8,5,3,2,1,1,0]
--

Binary Partitions:

数的二次幂拆分方法有多少种,其状态转移方程为:

则:

bpBar n
  | n == 0 = [1]
  | even n = let course = bpBar (n-1) in
             let pred = course !! 0 in                 -- bp (n-1)
             let half = course !! (n-1 - n `div` 2) in -- bp (n/2)
             pred + half : course
  | otherwise = let course = bpBar (n-1) in head course : course

-- >>> bpBar 20
-- [60,46,46,36,36,26,26,20,20,14,14,10,10,6,6,4,4,2,2,1,1]
--

但遗憾的是,其复杂度并不是O(n),因为每次都会索引链表,这很糟糕。

0-1背包问题:

其状态转移方程为:

这里也需要将这个n*W状态空间塞到course里:

则:

type Weight = Int
type Value = Double
type Items = [(Weight, Value)]

knapsack :: Items -> Weight -> Value
knapsack items capacity = head $ bar items capacity where
    bar :: Items -> Weight -> [Value]
    bar []             0 = [0]
    bar (_:items)      0 = 0 : bar items capacity
    bar []             y = 0 : bar []    (y-1)
    bar ((w, v):it
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值