这节课通过讲解动态规划在文本对齐(Text Justification)和黑杰克(Blackjack)上的求解过程,来帮助我们理解动态规划的通用求解的五个步骤: 动态规划求解的五个"简单"步骤: 定义子问题: 猜部分解决方法: 关联子问题的解决方法; 递归&记录 或者 构建自下向上的动态规划表: 解决原问题. 拿上节课的例子(斐波那契数和最短路径)来看,如下图所示: 一.文本对齐 首先,我们先看下文本对齐问题,在使用word排版文字的时候,为了排版美观,我们常会用到文本两端对齐…
这节课讲动态规划的内容,动态规划是一种通用且有效的算法设计思路,它的主要成分是"子问题"+"重用".它可以用于斐波那契和最短路径等问题的求解上. 一.斐波那契 首先,我们来看下斐波那契问题是什么?传统做法和动态规划法有什么区别? 从上图就能很明显地看出动态规划采用了memorization的思路,将历史计算结果保存下来,这样就能避免递归过程中的重复计算. 我们总结动态规划在求解斐波那契数的内容如下: 记录召回(Memorized calls)只花常数时间.动态规划大…
之前我们讲到动态规划五步中有个Guessing猜,一般情况下猜有两种情况: 在猜和递归上:猜的是用于解决更大问题的子问题: 在子问题定义上:如果要猜更多,就要增加更多子问题. 下面我们来看如果像背包问题那样子问题比较多,该怎么去解决? 一.Piano / Guitar Fingering 给定n个按键,找到每个键应该用哪只手指去按.假设有F个手指,刚开始手指f按在p键上,如果转移到用手指g按键q,这个转移难度为定义为d(p, f, q, g). 动态规划的解决思路如下(红叉内的内容是因为只考虑了…
这节课主要针对字符串/序列上的问题,了解如果使用动态规划进行求解.上节课我们也讲过使用前缀和后缀的概念,他们如下所示: 接下来,我们通过三个问题来深入了解下动态规划使用前缀.后缀和子串怎么去解决括号问题,编辑距离,背包问题. 一.括号问题 Parenthesization 在进行一些列矩阵乘法时,我们如果设计括号,可以使计算更加高效? 解决过程如下图所示: 子问题:求矩阵们A的最优相乘方式: 猜:上一次矩阵相乘应在哪? 递归:最小化矩阵相乘的损失: 拓扑排序:增加子串的大小: 原问题:DP(0,…
  Given n, how many structurally unique BST's (binary search trees) that store values 1...n? For example,Given n = 3, there are a total of 5 unique BST's. 1 3 3 2 1 \ / / / \ \ 3 2 1 1 3 2 / / \ \ 2 1 2 3 二叉排序树(二叉排序树(Binary Sort Tree)又称二叉查找树(Binary S…
Given an array of words and a length L, format the text such that each line has exactly L characters and is fully (left and right) justified. You should pack your words in a greedy approach; that is, pack as many words as you can in each line. Pad ex…
Given an array of words and a width maxWidth, format the text such that each line has exactly maxWidth characters and is fully (left and right) justified. You should pack your words in a greedy approach; that is, pack as many words as you can in each…
Given an array of words and a width maxWidth, format the text such that each line has exactly maxWidth characters and is fully (left and right) justified. You should pack your words in a greedy approach; that is, pack as many words as you can in each…
[抄题]: Given an array of words and a width maxWidth, format the text such that each line has exactly maxWidth characters and is fully (left and right) justified. You should pack your words in a greedy approach; that is, pack as many words as you can i…
Given an array of words and a width maxWidth, format the text such that each line has exactly maxWidth characters and is fully (left and right) justified. You should pack your words in a greedy approach; that is, pack as many words as you can in each…