Introduction to Algorithms (Dynamic Programming II: Text Justification, Blackjack)

5 easy steps to DP

  1. define subproblems #subproblems
  2. guess (part of the solution) #choices for guess
  3. relate subproblem solutions #time/subproblems
  4. recursive & memoize or build DP table bottom-up #check subproblem is acyclic
  5. solve original problem #extra time

Text justification

Split the text into "good" lines

  • obvious (MS Word/Open Office) algorithm: put as many words that fit on the first line, repeat
  • but this can make very bad lines
  • Define badness(i, j) for line of words[i : j]. For example, ∞ if total length > page width, else (page width − total length)^3.
  • goal: split words into lines to min \sum badness
  1. subproblems = min. badness for suffix words[i :] # subproblems = Θ(n) where n = # words
  2. guess: where to start the second line # guess <= n - i = O(n)
  3. recurrence:
    1. DP(i) = DP[i] = min(badness (i, j) + DP[j] for j in range (i + 1, n + 1))
    2. DP[n] = 0 ⇒ time per subproblem = Θ(n)
  4. order: for i = n, n − 1, . . . , 1, 0 total time = Θ(n^2)
  5. original problem: DP(0)

Parent Pointers

To recover actual solution in addition to cost, store parent pointers (which guess used at each subproblem) & walk back

  • typically: remember argmin/argmax in addition to min/max
  • just like memoization & bottom-up, this transformation is automatic
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值