Dynamic Programming Questions

High level thought

  • it is true that people claim DP is just an optimization of recursion. But in terms of writing actual code, how are they different?
  • How is recursion different from divide and conquer?

Questions

62. Unique Paths

1 Line Math Solution (Python)

def uniquePaths(self, m, n): 
    return math.factorial(m+n-2)/math.factorial(m-1)/math.factorial(n-1)

63. Unique Paths II

def uniquePathsWithObstacles(self, obstacleGrid): 
    m = len(obstacleGrid) 
    n = len(obstacleGrid[0]) 
    obstacleGrid[0][0] = 1 - obstacleGrid[0][0] 

    for i in range(1, n): 
        if not obstacleGrid[0][i]: 
            obstacleGrid[0][i] = obstacleGrid[0][i-1] 
        else: obstacleGrid[0][i] = 0 

    for i in range(1, m): 
        if not obstacleGrid[i][0]: 
            obstacleGrid[i][0] = obstacleGrid[i-1][0] 
        else: 
            obstacleGrid[i][0] = 0 
    
    for i in range(1, m): 
        for j in range(1, n): 
            if not obstacleGrid[i][j]: 
                obstacleGrid[i][j] = obstacleGrid[i][j-1]+obstacleGrid[i-1][j] 
            else: 
                obstacleGrid[i][j] = 0 

    return obstacleGrid[-1][-1]

A shorter version:

def uniquePathsWithObstacles(self, obstacleGrid): 
    m = len(obstacleGrid) 
    n = len(obstacleGrid[0]) 
    ResGrid = [[0 for x in range(n+1)] for x in range(m+1)] 
    ResGrid[0][1] = 1 

    for i in range(1, m+1): 
        for j in range(1, n+1): 
            if not obstacleGrid[i-1][j-1]: 
                ResGrid[i][j] = ResGrid[i][j-1]+ResGrid[i-1][j] 
    
    return ResGrid[m][n]

120. Triangle

# O(n*n/2) space, top-down 
def minimumTotal1(self, triangle): 
    if not triangle: return 
    
    res = [[0 for i in xrange(len(row))] for row in triangle] 
    res[0][0] = triangle[0][0] 
    for i in xrange(1, len(triangle)): 
        for j in xrange(len(triangle[i])): 
            if j == 0: 
                res[i][j] = res[i-1][j] + triangle[i][j] 
            elif j == len(triangle[i])-1: 
                res[i][j] = res[i-1][j-1] + triangle[i][j] 
            else: 
                res[i][j] = min(res[i-1][j-1], res[i-1][j]) + triangle[i][j] 
    
    return min(res[-1])
# Modify the original triangle, top-down
def minimumTotal2(self, triangle): 
    if not triangle: return 

    for i in xrange(1, len(triangle)): 
        for j in xrange(len(triangle[i])): 
            if j == 0: 
                triangle[i][j] += triangle[i-1][j] 
            elif j == len(triangle[i])-1: 
                triangle[i][j] += triangle[i-1][j-1] 
            else: 
                triangle[i][j] += min(triangle[i-1][j-1], triangle[i-1][j]) 

    return min(triangle[-1])

** don't understand these two bottom-up algm:

# Modify the original triangle, bottom-up
def minimumTotal3(self, triangle): 
    if not triangle: return 
    for i in xrange(len(triangle)-2, -1, -1): 
        for j in xrange(len(triangle[i])): 
            triangle[i][j] += min(triangle[i+1][j], triangle[i+1][j+1]) 
    return triangle[0][0]
# bottom-up, O(n) space
def minimumTotal(self, triangle): 
    if not triangle: return 
    res = triangle[-1] 
    for i in xrange(len(triangle)-2, -1, -1): 
        for j in xrange(len(triangle[i])): 
            res[j] = min(res[j], res[j+1]) + triangle[i][j] 
    return res[0]

64. Minimum Path Sum

def minPathSum(self, grid): 
    m = len(grid) 
    n = len(grid[0]) 
    for i in range(1, n): 
        grid[0][i] += grid[0][i-1] 
    for i in range(1, m): 
        grid[i][0] += grid[i-1][0] 
    
    for i in range(1, m): 
        for j in range(1, n): 
            grid[i][j] += min(grid[i-1][j], grid[i][j-1]) 
    
    return grid[-1][-1]

53. Maximum Subarray

Analysis of this problem: Apparently, this is a optimization problem, which can be usually solved by DP. So when it comes to DP, the first thing for us to figure out is the format of the sub problem(or the state of each sub problem). The format of the sub problem can be helpful when we are trying to come up with the recursive relation.

At first, I think the sub problem should look like: maxSubArray(int A[], int i, int j), which means the maxSubArray for A[i: j]. In this way, our goal is to figure out what maxSubArray(A, 0, A.length - 1) is. However, if we define the format of the sub problem in this way, it's hard to find the connection from the sub problem to the original problem(at least for me). In other words, I can't find a way to divided the original problem into the sub problems and use the solutions of the sub problems to somehow create the solution of the original one.

So I change the format of the sub problem into something like: maxSubArray(int A[], int i) , which means the maxSubArray for A[0:i ] which must has A[i] as the end element. Note that now the sub problem's format is less flexible and less powerful than the previous one because there's a limitation that A[i] should be contained in that sequence and we have to keep track of each solution of the sub problem to update the global optimal value. However, now the connect between the sub problem & the original one becomes clearer:

maxSubArray(A, i) = maxSubArray(A, i - 1) > 0 ? maxSubArray(A, i - 1) : 0 + A[i];

public int maxSubArray(int[] A) { 
    int n = A.length; 
    int[] dp = new int[n];//dp[i] means the maximum subarray ending with A[i]; 
    dp[0] = A[0]; 
    int max = dp[0]; 

    for(int i = 1; i < n; i++){ 
        dp[i] = A[i] + (dp[i - 1] > 0 ? dp[i - 1] : 0); 
        max = Math.max(max, dp[i]); 
    } 
    return max;
} 
class Solution {
    public: 
    int maxSubArray(int A[], int n) { 
        int ans=A[0],i,j,sum=0; 
        for(i=0;i<n;i++){ 
            sum+=A[i]; 
            ans=max(sum,ans); 
            sum=max(sum,0); 
        } 
        return ans; 
    }
};
def maxSubArray(self, A): 
    if not A: return 0 
    curSum = maxSum = A[0] 
    for num in A[1:]: 
        curSum = max(num, curSum + num) 
        maxSum = max(maxSum, curSum) 
    return maxSum

121. Best Time to Buy and Sell Stock

The question is simple. You want to find the difference of the maximum and the minimum. The only trick is that the bigger number should come after the smaller number.

So, here is how I tackled it. Instead of going forward, I scanned through the list of prices backward to store the current maximum number. Update the biggest difference along the way.

# backward iteration
def maxProfit(self, prices): 
    length = len(prices) 
    if length==0: return 0 
    maxPrice = prices[length-1] 
    res = 0 

    for i in range(length-1,-1,-1): 
        maxPrice = max(maxPrice ,prices[i]) 
        if maxPrice - prices[i] > res: 
            res = maxPrice - prices[i] 

    return res
# forward iteration
def maxProfit(self, prices): 
    if len(prices) == 0: return 0 
    minPrice = prices[0] 
    maxProfit = 0 
    
    for i in range(0, len(prices)): 
        if prices[i] < minPrice: 
            minPrice = prices[i] 
        if prices[i] - minPrice > maxProfit: 
            maxProfit = prices[i] - minPrice 
    
    return maxProfit

123. Best Time to Buy and Sell Stock III

A clean DP solution which generalizes to k transactions

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 206,378评论 6 481
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 88,356评论 2 382
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 152,702评论 0 342
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 55,259评论 1 279
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 64,263评论 5 371
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 49,036评论 1 285
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 38,349评论 3 400
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,979评论 0 259
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 43,469评论 1 300
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,938评论 2 323
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 38,059评论 1 333
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,703评论 4 323
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 39,257评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 30,262评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,485评论 1 262
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 45,501评论 2 354
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,792评论 2 345

推荐阅读更多精彩内容

  • **2014真题Directions:Read the following text. Choose the be...
    又是夜半惊坐起阅读 9,389评论 0 23
  • iOS10收到通知不再是在[application: didReceiveRemoteNotification:]...
    进击的小杰阅读 352评论 0 0
  • 毕业,曾经觉得遥远的名词,很快就要变成动词了。 想想,自从大四上半学期结束后,我就进入了一段醉生梦死的时间,迷迷茫...
    零兰阅读 190评论 5 3